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.ArrayContainsAll: lambda self, e: self.binary(e, "@>"), 118 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 119 exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}", 120 exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}", 121 exp.CaseSpecificColumnConstraint: lambda _, 122 e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC", 123 exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}", 124 exp.CharacterSetProperty: lambda self, 125 e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}", 126 exp.ClusteredColumnConstraint: lambda self, 127 e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})", 128 exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}", 129 exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}", 130 exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}", 131 exp.CopyGrantsProperty: lambda *_: "COPY GRANTS", 132 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 133 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 134 exp.DynamicProperty: lambda *_: "DYNAMIC", 135 exp.EmptyProperty: lambda *_: "EMPTY", 136 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 137 exp.EphemeralColumnConstraint: lambda self, 138 e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}", 139 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 140 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 141 exp.Except: lambda self, e: self.set_operations(e), 142 exp.ExternalProperty: lambda *_: "EXTERNAL", 143 exp.GlobalProperty: lambda *_: "GLOBAL", 144 exp.HeapProperty: lambda *_: "HEAP", 145 exp.IcebergProperty: lambda *_: "ICEBERG", 146 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 147 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 148 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 149 exp.Intersect: lambda self, e: self.set_operations(e), 150 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 151 exp.LanguageProperty: lambda self, e: self.naked_property(e), 152 exp.LocationProperty: lambda self, e: self.naked_property(e), 153 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 154 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 155 exp.NonClusteredColumnConstraint: lambda self, 156 e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})", 157 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 158 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 159 exp.OnCommitProperty: lambda _, 160 e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS", 161 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 162 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 163 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 164 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 165 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 166 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 167 exp.ProjectionPolicyColumnConstraint: lambda self, 168 e: f"PROJECTION POLICY {self.sql(e, 'this')}", 169 exp.RemoteWithConnectionModelProperty: lambda self, 170 e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}", 171 exp.ReturnsProperty: lambda self, e: ( 172 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 173 ), 174 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 175 exp.SecureProperty: lambda *_: "SECURE", 176 exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}", 177 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 178 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 179 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 180 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 181 exp.SqlReadWriteProperty: lambda _, e: e.name, 182 exp.SqlSecurityProperty: lambda _, 183 e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}", 184 exp.StabilityProperty: lambda _, e: e.name, 185 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 186 exp.StreamingTableProperty: lambda *_: "STREAMING", 187 exp.StrictProperty: lambda *_: "STRICT", 188 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 189 exp.TemporaryProperty: lambda *_: "TEMPORARY", 190 exp.TagColumnConstraint: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 191 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 192 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 193 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 194 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 195 exp.TransientProperty: lambda *_: "TRANSIENT", 196 exp.Union: lambda self, e: self.set_operations(e), 197 exp.UnloggedProperty: lambda *_: "UNLOGGED", 198 exp.Uuid: lambda *_: "UUID()", 199 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 200 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 201 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 202 exp.VolatileProperty: lambda *_: "VOLATILE", 203 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 204 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 205 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 206 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 207 } 208 209 # Whether null ordering is supported in order by 210 # True: Full Support, None: No support, False: No support for certain cases 211 # such as window specifications, aggregate functions etc 212 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 213 214 # Whether ignore nulls is inside the agg or outside. 215 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 216 IGNORE_NULLS_IN_FUNC = False 217 218 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 219 LOCKING_READS_SUPPORTED = False 220 221 # Whether the EXCEPT and INTERSECT operations can return duplicates 222 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 223 224 # Wrap derived values in parens, usually standard but spark doesn't support it 225 WRAP_DERIVED_VALUES = True 226 227 # Whether create function uses an AS before the RETURN 228 CREATE_FUNCTION_RETURN_AS = True 229 230 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 231 MATCHED_BY_SOURCE = True 232 233 # Whether the INTERVAL expression works only with values like '1 day' 234 SINGLE_STRING_INTERVAL = False 235 236 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 237 INTERVAL_ALLOWS_PLURAL_FORM = True 238 239 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 240 LIMIT_FETCH = "ALL" 241 242 # Whether limit and fetch allows expresions or just limits 243 LIMIT_ONLY_LITERALS = False 244 245 # Whether a table is allowed to be renamed with a db 246 RENAME_TABLE_WITH_DB = True 247 248 # The separator for grouping sets and rollups 249 GROUPINGS_SEP = "," 250 251 # The string used for creating an index on a table 252 INDEX_ON = "ON" 253 254 # Whether join hints should be generated 255 JOIN_HINTS = True 256 257 # Whether table hints should be generated 258 TABLE_HINTS = True 259 260 # Whether query hints should be generated 261 QUERY_HINTS = True 262 263 # What kind of separator to use for query hints 264 QUERY_HINT_SEP = ", " 265 266 # Whether comparing against booleans (e.g. x IS TRUE) is supported 267 IS_BOOL_ALLOWED = True 268 269 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 270 DUPLICATE_KEY_UPDATE_WITH_SET = True 271 272 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 273 LIMIT_IS_TOP = False 274 275 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 276 RETURNING_END = True 277 278 # Whether to generate an unquoted value for EXTRACT's date part argument 279 EXTRACT_ALLOWS_QUOTES = True 280 281 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 282 TZ_TO_WITH_TIME_ZONE = False 283 284 # Whether the NVL2 function is supported 285 NVL2_SUPPORTED = True 286 287 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 288 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 289 290 # Whether VALUES statements can be used as derived tables. 291 # MySQL 5 and Redshift do not allow this, so when False, it will convert 292 # SELECT * VALUES into SELECT UNION 293 VALUES_AS_TABLE = True 294 295 # Whether the word COLUMN is included when adding a column with ALTER TABLE 296 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 297 298 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 299 UNNEST_WITH_ORDINALITY = True 300 301 # Whether FILTER (WHERE cond) can be used for conditional aggregation 302 AGGREGATE_FILTER_SUPPORTED = True 303 304 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 305 SEMI_ANTI_JOIN_WITH_SIDE = True 306 307 # Whether to include the type of a computed column in the CREATE DDL 308 COMPUTED_COLUMN_WITH_TYPE = True 309 310 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 311 SUPPORTS_TABLE_COPY = True 312 313 # Whether parentheses are required around the table sample's expression 314 TABLESAMPLE_REQUIRES_PARENS = True 315 316 # Whether a table sample clause's size needs to be followed by the ROWS keyword 317 TABLESAMPLE_SIZE_IS_ROWS = True 318 319 # The keyword(s) to use when generating a sample clause 320 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 321 322 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 323 TABLESAMPLE_WITH_METHOD = True 324 325 # The keyword to use when specifying the seed of a sample clause 326 TABLESAMPLE_SEED_KEYWORD = "SEED" 327 328 # Whether COLLATE is a function instead of a binary operator 329 COLLATE_IS_FUNC = False 330 331 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 332 DATA_TYPE_SPECIFIERS_ALLOWED = False 333 334 # Whether conditions require booleans WHERE x = 0 vs WHERE x 335 ENSURE_BOOLS = False 336 337 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 338 CTE_RECURSIVE_KEYWORD_REQUIRED = True 339 340 # Whether CONCAT requires >1 arguments 341 SUPPORTS_SINGLE_ARG_CONCAT = True 342 343 # Whether LAST_DAY function supports a date part argument 344 LAST_DAY_SUPPORTS_DATE_PART = True 345 346 # Whether named columns are allowed in table aliases 347 SUPPORTS_TABLE_ALIAS_COLUMNS = True 348 349 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 350 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 351 352 # What delimiter to use for separating JSON key/value pairs 353 JSON_KEY_VALUE_PAIR_SEP = ":" 354 355 # INSERT OVERWRITE TABLE x override 356 INSERT_OVERWRITE = " OVERWRITE TABLE" 357 358 # Whether the SELECT .. INTO syntax is used instead of CTAS 359 SUPPORTS_SELECT_INTO = False 360 361 # Whether UNLOGGED tables can be created 362 SUPPORTS_UNLOGGED_TABLES = False 363 364 # Whether the CREATE TABLE LIKE statement is supported 365 SUPPORTS_CREATE_TABLE_LIKE = True 366 367 # Whether the LikeProperty needs to be specified inside of the schema clause 368 LIKE_PROPERTY_INSIDE_SCHEMA = False 369 370 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 371 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 372 MULTI_ARG_DISTINCT = True 373 374 # Whether the JSON extraction operators expect a value of type JSON 375 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 376 377 # Whether bracketed keys like ["foo"] are supported in JSON paths 378 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 379 380 # Whether to escape keys using single quotes in JSON paths 381 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 382 383 # The JSONPathPart expressions supported by this dialect 384 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 385 386 # Whether any(f(x) for x in array) can be implemented by this dialect 387 CAN_IMPLEMENT_ARRAY_ANY = False 388 389 # Whether the function TO_NUMBER is supported 390 SUPPORTS_TO_NUMBER = True 391 392 # Whether or not set op modifiers apply to the outer set op or select. 393 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 394 # True means limit 1 happens after the set op, False means it it happens on y. 395 SET_OP_MODIFIERS = True 396 397 # Whether parameters from COPY statement are wrapped in parentheses 398 COPY_PARAMS_ARE_WRAPPED = True 399 400 # Whether values of params are set with "=" token or empty space 401 COPY_PARAMS_EQ_REQUIRED = False 402 403 # Whether COPY statement has INTO keyword 404 COPY_HAS_INTO_KEYWORD = True 405 406 # Whether the conditional TRY(expression) function is supported 407 TRY_SUPPORTED = True 408 409 # Whether the UESCAPE syntax in unicode strings is supported 410 SUPPORTS_UESCAPE = True 411 412 # The keyword to use when generating a star projection with excluded columns 413 STAR_EXCEPT = "EXCEPT" 414 415 # The HEX function name 416 HEX_FUNC = "HEX" 417 418 # The keywords to use when prefixing & separating WITH based properties 419 WITH_PROPERTIES_PREFIX = "WITH" 420 421 # Whether to quote the generated expression of exp.JsonPath 422 QUOTE_JSON_PATH = True 423 424 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 425 PAD_FILL_PATTERN_IS_REQUIRED = False 426 427 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 428 SUPPORTS_EXPLODING_PROJECTIONS = True 429 430 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 431 ARRAY_CONCAT_IS_VAR_LEN = True 432 433 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 434 SUPPORTS_CONVERT_TIMEZONE = False 435 436 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 437 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 438 439 TYPE_MAPPING = { 440 exp.DataType.Type.NCHAR: "CHAR", 441 exp.DataType.Type.NVARCHAR: "VARCHAR", 442 exp.DataType.Type.MEDIUMTEXT: "TEXT", 443 exp.DataType.Type.LONGTEXT: "TEXT", 444 exp.DataType.Type.TINYTEXT: "TEXT", 445 exp.DataType.Type.MEDIUMBLOB: "BLOB", 446 exp.DataType.Type.LONGBLOB: "BLOB", 447 exp.DataType.Type.TINYBLOB: "BLOB", 448 exp.DataType.Type.INET: "INET", 449 exp.DataType.Type.ROWVERSION: "VARBINARY", 450 } 451 452 TIME_PART_SINGULARS = { 453 "MICROSECONDS": "MICROSECOND", 454 "SECONDS": "SECOND", 455 "MINUTES": "MINUTE", 456 "HOURS": "HOUR", 457 "DAYS": "DAY", 458 "WEEKS": "WEEK", 459 "MONTHS": "MONTH", 460 "QUARTERS": "QUARTER", 461 "YEARS": "YEAR", 462 } 463 464 AFTER_HAVING_MODIFIER_TRANSFORMS = { 465 "cluster": lambda self, e: self.sql(e, "cluster"), 466 "distribute": lambda self, e: self.sql(e, "distribute"), 467 "sort": lambda self, e: self.sql(e, "sort"), 468 "windows": lambda self, e: ( 469 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 470 if e.args.get("windows") 471 else "" 472 ), 473 "qualify": lambda self, e: self.sql(e, "qualify"), 474 } 475 476 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 477 478 STRUCT_DELIMITER = ("<", ">") 479 480 PARAMETER_TOKEN = "@" 481 NAMED_PLACEHOLDER_TOKEN = ":" 482 483 PROPERTIES_LOCATION = { 484 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 485 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 486 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 487 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 488 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 489 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 490 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 491 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 492 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 493 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 494 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 495 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 496 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 497 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 498 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 499 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 500 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 501 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 502 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 503 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 504 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 505 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 506 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 507 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 508 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 509 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 510 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 511 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 512 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 513 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 514 exp.HeapProperty: exp.Properties.Location.POST_WITH, 515 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 516 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 517 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 518 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 519 exp.JournalProperty: exp.Properties.Location.POST_NAME, 520 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 521 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 522 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 523 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 524 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 525 exp.LogProperty: exp.Properties.Location.POST_NAME, 526 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 527 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 528 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 529 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 530 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 531 exp.Order: exp.Properties.Location.POST_SCHEMA, 532 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 533 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 534 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 535 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 536 exp.Property: exp.Properties.Location.POST_WITH, 537 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 538 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 539 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 540 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 541 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 542 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 543 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 544 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 545 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 546 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 547 exp.Set: exp.Properties.Location.POST_SCHEMA, 548 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 549 exp.SetProperty: exp.Properties.Location.POST_CREATE, 550 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 551 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 552 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 553 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 554 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 555 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 556 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 557 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 558 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 559 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 560 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 561 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 562 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 563 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 564 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 565 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 566 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 567 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 568 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 569 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 570 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 571 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 572 } 573 574 # Keywords that can't be used as unquoted identifier names 575 RESERVED_KEYWORDS: t.Set[str] = set() 576 577 # Expressions whose comments are separated from them for better formatting 578 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 579 exp.Command, 580 exp.Create, 581 exp.Delete, 582 exp.Drop, 583 exp.From, 584 exp.Insert, 585 exp.Join, 586 exp.MultitableInserts, 587 exp.Select, 588 exp.SetOperation, 589 exp.Update, 590 exp.Where, 591 exp.With, 592 ) 593 594 # Expressions that should not have their comments generated in maybe_comment 595 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 596 exp.Binary, 597 exp.SetOperation, 598 ) 599 600 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 601 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 602 exp.Column, 603 exp.Literal, 604 exp.Neg, 605 exp.Paren, 606 ) 607 608 PARAMETERIZABLE_TEXT_TYPES = { 609 exp.DataType.Type.NVARCHAR, 610 exp.DataType.Type.VARCHAR, 611 exp.DataType.Type.CHAR, 612 exp.DataType.Type.NCHAR, 613 } 614 615 # Expressions that need to have all CTEs under them bubbled up to them 616 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 617 618 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 619 620 __slots__ = ( 621 "pretty", 622 "identify", 623 "normalize", 624 "pad", 625 "_indent", 626 "normalize_functions", 627 "unsupported_level", 628 "max_unsupported", 629 "leading_comma", 630 "max_text_width", 631 "comments", 632 "dialect", 633 "unsupported_messages", 634 "_escaped_quote_end", 635 "_escaped_identifier_end", 636 "_next_name", 637 "_identifier_start", 638 "_identifier_end", 639 ) 640 641 def __init__( 642 self, 643 pretty: t.Optional[bool] = None, 644 identify: str | bool = False, 645 normalize: bool = False, 646 pad: int = 2, 647 indent: int = 2, 648 normalize_functions: t.Optional[str | bool] = None, 649 unsupported_level: ErrorLevel = ErrorLevel.WARN, 650 max_unsupported: int = 3, 651 leading_comma: bool = False, 652 max_text_width: int = 80, 653 comments: bool = True, 654 dialect: DialectType = None, 655 ): 656 import sqlglot 657 from sqlglot.dialects import Dialect 658 659 self.pretty = pretty if pretty is not None else sqlglot.pretty 660 self.identify = identify 661 self.normalize = normalize 662 self.pad = pad 663 self._indent = indent 664 self.unsupported_level = unsupported_level 665 self.max_unsupported = max_unsupported 666 self.leading_comma = leading_comma 667 self.max_text_width = max_text_width 668 self.comments = comments 669 self.dialect = Dialect.get_or_raise(dialect) 670 671 # This is both a Dialect property and a Generator argument, so we prioritize the latter 672 self.normalize_functions = ( 673 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 674 ) 675 676 self.unsupported_messages: t.List[str] = [] 677 self._escaped_quote_end: str = ( 678 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 679 ) 680 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 681 682 self._next_name = name_sequence("_t") 683 684 self._identifier_start = self.dialect.IDENTIFIER_START 685 self._identifier_end = self.dialect.IDENTIFIER_END 686 687 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 688 """ 689 Generates the SQL string corresponding to the given syntax tree. 690 691 Args: 692 expression: The syntax tree. 693 copy: Whether to copy the expression. The generator performs mutations so 694 it is safer to copy. 695 696 Returns: 697 The SQL string corresponding to `expression`. 698 """ 699 if copy: 700 expression = expression.copy() 701 702 expression = self.preprocess(expression) 703 704 self.unsupported_messages = [] 705 sql = self.sql(expression).strip() 706 707 if self.pretty: 708 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 709 710 if self.unsupported_level == ErrorLevel.IGNORE: 711 return sql 712 713 if self.unsupported_level == ErrorLevel.WARN: 714 for msg in self.unsupported_messages: 715 logger.warning(msg) 716 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 717 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 718 719 return sql 720 721 def preprocess(self, expression: exp.Expression) -> exp.Expression: 722 """Apply generic preprocessing transformations to a given expression.""" 723 expression = self._move_ctes_to_top_level(expression) 724 725 if self.ENSURE_BOOLS: 726 from sqlglot.transforms import ensure_bools 727 728 expression = ensure_bools(expression) 729 730 return expression 731 732 def _move_ctes_to_top_level(self, expression: E) -> E: 733 if ( 734 not expression.parent 735 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 736 and any(node.parent is not expression for node in expression.find_all(exp.With)) 737 ): 738 from sqlglot.transforms import move_ctes_to_top_level 739 740 expression = move_ctes_to_top_level(expression) 741 return expression 742 743 def unsupported(self, message: str) -> None: 744 if self.unsupported_level == ErrorLevel.IMMEDIATE: 745 raise UnsupportedError(message) 746 self.unsupported_messages.append(message) 747 748 def sep(self, sep: str = " ") -> str: 749 return f"{sep.strip()}\n" if self.pretty else sep 750 751 def seg(self, sql: str, sep: str = " ") -> str: 752 return f"{self.sep(sep)}{sql}" 753 754 def pad_comment(self, comment: str) -> str: 755 comment = " " + comment if comment[0].strip() else comment 756 comment = comment + " " if comment[-1].strip() else comment 757 return comment 758 759 def maybe_comment( 760 self, 761 sql: str, 762 expression: t.Optional[exp.Expression] = None, 763 comments: t.Optional[t.List[str]] = None, 764 separated: bool = False, 765 ) -> str: 766 comments = ( 767 ((expression and expression.comments) if comments is None else comments) # type: ignore 768 if self.comments 769 else None 770 ) 771 772 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 773 return sql 774 775 comments_sql = " ".join( 776 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 777 ) 778 779 if not comments_sql: 780 return sql 781 782 comments_sql = self._replace_line_breaks(comments_sql) 783 784 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 785 return ( 786 f"{self.sep()}{comments_sql}{sql}" 787 if not sql or sql[0].isspace() 788 else f"{comments_sql}{self.sep()}{sql}" 789 ) 790 791 return f"{sql} {comments_sql}" 792 793 def wrap(self, expression: exp.Expression | str) -> str: 794 this_sql = ( 795 self.sql(expression) 796 if isinstance(expression, exp.UNWRAPPED_QUERIES) 797 else self.sql(expression, "this") 798 ) 799 if not this_sql: 800 return "()" 801 802 this_sql = self.indent(this_sql, level=1, pad=0) 803 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 804 805 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 806 original = self.identify 807 self.identify = False 808 result = func(*args, **kwargs) 809 self.identify = original 810 return result 811 812 def normalize_func(self, name: str) -> str: 813 if self.normalize_functions == "upper" or self.normalize_functions is True: 814 return name.upper() 815 if self.normalize_functions == "lower": 816 return name.lower() 817 return name 818 819 def indent( 820 self, 821 sql: str, 822 level: int = 0, 823 pad: t.Optional[int] = None, 824 skip_first: bool = False, 825 skip_last: bool = False, 826 ) -> str: 827 if not self.pretty or not sql: 828 return sql 829 830 pad = self.pad if pad is None else pad 831 lines = sql.split("\n") 832 833 return "\n".join( 834 ( 835 line 836 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 837 else f"{' ' * (level * self._indent + pad)}{line}" 838 ) 839 for i, line in enumerate(lines) 840 ) 841 842 def sql( 843 self, 844 expression: t.Optional[str | exp.Expression], 845 key: t.Optional[str] = None, 846 comment: bool = True, 847 ) -> str: 848 if not expression: 849 return "" 850 851 if isinstance(expression, str): 852 return expression 853 854 if key: 855 value = expression.args.get(key) 856 if value: 857 return self.sql(value) 858 return "" 859 860 transform = self.TRANSFORMS.get(expression.__class__) 861 862 if callable(transform): 863 sql = transform(self, expression) 864 elif isinstance(expression, exp.Expression): 865 exp_handler_name = f"{expression.key}_sql" 866 867 if hasattr(self, exp_handler_name): 868 sql = getattr(self, exp_handler_name)(expression) 869 elif isinstance(expression, exp.Func): 870 sql = self.function_fallback_sql(expression) 871 elif isinstance(expression, exp.Property): 872 sql = self.property_sql(expression) 873 else: 874 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 875 else: 876 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 877 878 return self.maybe_comment(sql, expression) if self.comments and comment else sql 879 880 def uncache_sql(self, expression: exp.Uncache) -> str: 881 table = self.sql(expression, "this") 882 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 883 return f"UNCACHE TABLE{exists_sql} {table}" 884 885 def cache_sql(self, expression: exp.Cache) -> str: 886 lazy = " LAZY" if expression.args.get("lazy") else "" 887 table = self.sql(expression, "this") 888 options = expression.args.get("options") 889 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 890 sql = self.sql(expression, "expression") 891 sql = f" AS{self.sep()}{sql}" if sql else "" 892 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 893 return self.prepend_ctes(expression, sql) 894 895 def characterset_sql(self, expression: exp.CharacterSet) -> str: 896 if isinstance(expression.parent, exp.Cast): 897 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 898 default = "DEFAULT " if expression.args.get("default") else "" 899 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 900 901 def column_parts(self, expression: exp.Column) -> str: 902 return ".".join( 903 self.sql(part) 904 for part in ( 905 expression.args.get("catalog"), 906 expression.args.get("db"), 907 expression.args.get("table"), 908 expression.args.get("this"), 909 ) 910 if part 911 ) 912 913 def column_sql(self, expression: exp.Column) -> str: 914 join_mark = " (+)" if expression.args.get("join_mark") else "" 915 916 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 917 join_mark = "" 918 self.unsupported("Outer join syntax using the (+) operator is not supported.") 919 920 return f"{self.column_parts(expression)}{join_mark}" 921 922 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 923 this = self.sql(expression, "this") 924 this = f" {this}" if this else "" 925 position = self.sql(expression, "position") 926 return f"{position}{this}" 927 928 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 929 column = self.sql(expression, "this") 930 kind = self.sql(expression, "kind") 931 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 932 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 933 kind = f"{sep}{kind}" if kind else "" 934 constraints = f" {constraints}" if constraints else "" 935 position = self.sql(expression, "position") 936 position = f" {position}" if position else "" 937 938 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 939 kind = "" 940 941 return f"{exists}{column}{kind}{constraints}{position}" 942 943 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 944 this = self.sql(expression, "this") 945 kind_sql = self.sql(expression, "kind").strip() 946 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 947 948 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 949 this = self.sql(expression, "this") 950 if expression.args.get("not_null"): 951 persisted = " PERSISTED NOT NULL" 952 elif expression.args.get("persisted"): 953 persisted = " PERSISTED" 954 else: 955 persisted = "" 956 return f"AS {this}{persisted}" 957 958 def autoincrementcolumnconstraint_sql(self, _) -> str: 959 return self.token_sql(TokenType.AUTO_INCREMENT) 960 961 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 962 if isinstance(expression.this, list): 963 this = self.wrap(self.expressions(expression, key="this", flat=True)) 964 else: 965 this = self.sql(expression, "this") 966 967 return f"COMPRESS {this}" 968 969 def generatedasidentitycolumnconstraint_sql( 970 self, expression: exp.GeneratedAsIdentityColumnConstraint 971 ) -> str: 972 this = "" 973 if expression.this is not None: 974 on_null = " ON NULL" if expression.args.get("on_null") else "" 975 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 976 977 start = expression.args.get("start") 978 start = f"START WITH {start}" if start else "" 979 increment = expression.args.get("increment") 980 increment = f" INCREMENT BY {increment}" if increment else "" 981 minvalue = expression.args.get("minvalue") 982 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 983 maxvalue = expression.args.get("maxvalue") 984 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 985 cycle = expression.args.get("cycle") 986 cycle_sql = "" 987 988 if cycle is not None: 989 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 990 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 991 992 sequence_opts = "" 993 if start or increment or cycle_sql: 994 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 995 sequence_opts = f" ({sequence_opts.strip()})" 996 997 expr = self.sql(expression, "expression") 998 expr = f"({expr})" if expr else "IDENTITY" 999 1000 return f"GENERATED{this} AS {expr}{sequence_opts}" 1001 1002 def generatedasrowcolumnconstraint_sql( 1003 self, expression: exp.GeneratedAsRowColumnConstraint 1004 ) -> str: 1005 start = "START" if expression.args.get("start") else "END" 1006 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1007 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1008 1009 def periodforsystemtimeconstraint_sql( 1010 self, expression: exp.PeriodForSystemTimeConstraint 1011 ) -> str: 1012 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1013 1014 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1015 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1016 1017 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1018 return f"AS {self.sql(expression, 'this')}" 1019 1020 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1021 desc = expression.args.get("desc") 1022 if desc is not None: 1023 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1024 return "PRIMARY KEY" 1025 1026 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1027 this = self.sql(expression, "this") 1028 this = f" {this}" if this else "" 1029 index_type = expression.args.get("index_type") 1030 index_type = f" USING {index_type}" if index_type else "" 1031 on_conflict = self.sql(expression, "on_conflict") 1032 on_conflict = f" {on_conflict}" if on_conflict else "" 1033 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1034 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1035 1036 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1037 return self.sql(expression, "this") 1038 1039 def create_sql(self, expression: exp.Create) -> str: 1040 kind = self.sql(expression, "kind") 1041 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1042 properties = expression.args.get("properties") 1043 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1044 1045 this = self.createable_sql(expression, properties_locs) 1046 1047 properties_sql = "" 1048 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1049 exp.Properties.Location.POST_WITH 1050 ): 1051 properties_sql = self.sql( 1052 exp.Properties( 1053 expressions=[ 1054 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1055 *properties_locs[exp.Properties.Location.POST_WITH], 1056 ] 1057 ) 1058 ) 1059 1060 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1061 properties_sql = self.sep() + properties_sql 1062 elif not self.pretty: 1063 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1064 properties_sql = f" {properties_sql}" 1065 1066 begin = " BEGIN" if expression.args.get("begin") else "" 1067 end = " END" if expression.args.get("end") else "" 1068 1069 expression_sql = self.sql(expression, "expression") 1070 if expression_sql: 1071 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1072 1073 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1074 postalias_props_sql = "" 1075 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1076 postalias_props_sql = self.properties( 1077 exp.Properties( 1078 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1079 ), 1080 wrapped=False, 1081 ) 1082 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1083 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1084 1085 postindex_props_sql = "" 1086 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1087 postindex_props_sql = self.properties( 1088 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1089 wrapped=False, 1090 prefix=" ", 1091 ) 1092 1093 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1094 indexes = f" {indexes}" if indexes else "" 1095 index_sql = indexes + postindex_props_sql 1096 1097 replace = " OR REPLACE" if expression.args.get("replace") else "" 1098 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1099 unique = " UNIQUE" if expression.args.get("unique") else "" 1100 1101 clustered = expression.args.get("clustered") 1102 if clustered is None: 1103 clustered_sql = "" 1104 elif clustered: 1105 clustered_sql = " CLUSTERED COLUMNSTORE" 1106 else: 1107 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1108 1109 postcreate_props_sql = "" 1110 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1111 postcreate_props_sql = self.properties( 1112 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1113 sep=" ", 1114 prefix=" ", 1115 wrapped=False, 1116 ) 1117 1118 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1119 1120 postexpression_props_sql = "" 1121 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1122 postexpression_props_sql = self.properties( 1123 exp.Properties( 1124 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1125 ), 1126 sep=" ", 1127 prefix=" ", 1128 wrapped=False, 1129 ) 1130 1131 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1132 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1133 no_schema_binding = ( 1134 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1135 ) 1136 1137 clone = self.sql(expression, "clone") 1138 clone = f" {clone}" if clone else "" 1139 1140 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1141 return self.prepend_ctes(expression, expression_sql) 1142 1143 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1144 start = self.sql(expression, "start") 1145 start = f"START WITH {start}" if start else "" 1146 increment = self.sql(expression, "increment") 1147 increment = f" INCREMENT BY {increment}" if increment else "" 1148 minvalue = self.sql(expression, "minvalue") 1149 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1150 maxvalue = self.sql(expression, "maxvalue") 1151 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1152 owned = self.sql(expression, "owned") 1153 owned = f" OWNED BY {owned}" if owned else "" 1154 1155 cache = expression.args.get("cache") 1156 if cache is None: 1157 cache_str = "" 1158 elif cache is True: 1159 cache_str = " CACHE" 1160 else: 1161 cache_str = f" CACHE {cache}" 1162 1163 options = self.expressions(expression, key="options", flat=True, sep=" ") 1164 options = f" {options}" if options else "" 1165 1166 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1167 1168 def clone_sql(self, expression: exp.Clone) -> str: 1169 this = self.sql(expression, "this") 1170 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1171 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1172 return f"{shallow}{keyword} {this}" 1173 1174 def describe_sql(self, expression: exp.Describe) -> str: 1175 style = expression.args.get("style") 1176 style = f" {style}" if style else "" 1177 partition = self.sql(expression, "partition") 1178 partition = f" {partition}" if partition else "" 1179 return f"DESCRIBE{style} {self.sql(expression, 'this')}{partition}" 1180 1181 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1182 tag = self.sql(expression, "tag") 1183 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1184 1185 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1186 with_ = self.sql(expression, "with") 1187 if with_: 1188 sql = f"{with_}{self.sep()}{sql}" 1189 return sql 1190 1191 def with_sql(self, expression: exp.With) -> str: 1192 sql = self.expressions(expression, flat=True) 1193 recursive = ( 1194 "RECURSIVE " 1195 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1196 else "" 1197 ) 1198 1199 return f"WITH {recursive}{sql}" 1200 1201 def cte_sql(self, expression: exp.CTE) -> str: 1202 alias = expression.args.get("alias") 1203 if alias: 1204 alias.add_comments(expression.pop_comments()) 1205 1206 alias_sql = self.sql(expression, "alias") 1207 1208 materialized = expression.args.get("materialized") 1209 if materialized is False: 1210 materialized = "NOT MATERIALIZED " 1211 elif materialized: 1212 materialized = "MATERIALIZED " 1213 1214 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1215 1216 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1217 alias = self.sql(expression, "this") 1218 columns = self.expressions(expression, key="columns", flat=True) 1219 columns = f"({columns})" if columns else "" 1220 1221 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1222 columns = "" 1223 self.unsupported("Named columns are not supported in table alias.") 1224 1225 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1226 alias = self._next_name() 1227 1228 return f"{alias}{columns}" 1229 1230 def bitstring_sql(self, expression: exp.BitString) -> str: 1231 this = self.sql(expression, "this") 1232 if self.dialect.BIT_START: 1233 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1234 return f"{int(this, 2)}" 1235 1236 def hexstring_sql(self, expression: exp.HexString) -> str: 1237 this = self.sql(expression, "this") 1238 if self.dialect.HEX_START: 1239 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1240 return f"{int(this, 16)}" 1241 1242 def bytestring_sql(self, expression: exp.ByteString) -> str: 1243 this = self.sql(expression, "this") 1244 if self.dialect.BYTE_START: 1245 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1246 return this 1247 1248 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1249 this = self.sql(expression, "this") 1250 escape = expression.args.get("escape") 1251 1252 if self.dialect.UNICODE_START: 1253 escape_substitute = r"\\\1" 1254 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1255 else: 1256 escape_substitute = r"\\u\1" 1257 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1258 1259 if escape: 1260 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1261 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1262 else: 1263 escape_pattern = ESCAPED_UNICODE_RE 1264 escape_sql = "" 1265 1266 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1267 this = escape_pattern.sub(escape_substitute, this) 1268 1269 return f"{left_quote}{this}{right_quote}{escape_sql}" 1270 1271 def rawstring_sql(self, expression: exp.RawString) -> str: 1272 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1273 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1274 1275 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1276 this = self.sql(expression, "this") 1277 specifier = self.sql(expression, "expression") 1278 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1279 return f"{this}{specifier}" 1280 1281 def datatype_sql(self, expression: exp.DataType) -> str: 1282 nested = "" 1283 values = "" 1284 interior = self.expressions(expression, flat=True) 1285 1286 type_value = expression.this 1287 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1288 type_sql = self.sql(expression, "kind") 1289 else: 1290 type_sql = ( 1291 self.TYPE_MAPPING.get(type_value, type_value.value) 1292 if isinstance(type_value, exp.DataType.Type) 1293 else type_value 1294 ) 1295 1296 if interior: 1297 if expression.args.get("nested"): 1298 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1299 if expression.args.get("values") is not None: 1300 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1301 values = self.expressions(expression, key="values", flat=True) 1302 values = f"{delimiters[0]}{values}{delimiters[1]}" 1303 elif type_value == exp.DataType.Type.INTERVAL: 1304 nested = f" {interior}" 1305 else: 1306 nested = f"({interior})" 1307 1308 type_sql = f"{type_sql}{nested}{values}" 1309 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1310 exp.DataType.Type.TIMETZ, 1311 exp.DataType.Type.TIMESTAMPTZ, 1312 ): 1313 type_sql = f"{type_sql} WITH TIME ZONE" 1314 1315 return type_sql 1316 1317 def directory_sql(self, expression: exp.Directory) -> str: 1318 local = "LOCAL " if expression.args.get("local") else "" 1319 row_format = self.sql(expression, "row_format") 1320 row_format = f" {row_format}" if row_format else "" 1321 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1322 1323 def delete_sql(self, expression: exp.Delete) -> str: 1324 this = self.sql(expression, "this") 1325 this = f" FROM {this}" if this else "" 1326 using = self.sql(expression, "using") 1327 using = f" USING {using}" if using else "" 1328 cluster = self.sql(expression, "cluster") 1329 cluster = f" {cluster}" if cluster else "" 1330 where = self.sql(expression, "where") 1331 returning = self.sql(expression, "returning") 1332 limit = self.sql(expression, "limit") 1333 tables = self.expressions(expression, key="tables") 1334 tables = f" {tables}" if tables else "" 1335 if self.RETURNING_END: 1336 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1337 else: 1338 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1339 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1340 1341 def drop_sql(self, expression: exp.Drop) -> str: 1342 this = self.sql(expression, "this") 1343 expressions = self.expressions(expression, flat=True) 1344 expressions = f" ({expressions})" if expressions else "" 1345 kind = expression.args["kind"] 1346 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1347 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1348 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1349 on_cluster = self.sql(expression, "cluster") 1350 on_cluster = f" {on_cluster}" if on_cluster else "" 1351 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1352 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1353 cascade = " CASCADE" if expression.args.get("cascade") else "" 1354 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1355 purge = " PURGE" if expression.args.get("purge") else "" 1356 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1357 1358 def set_operation(self, expression: exp.SetOperation) -> str: 1359 op_type = type(expression) 1360 op_name = op_type.key.upper() 1361 1362 distinct = expression.args.get("distinct") 1363 if ( 1364 distinct is False 1365 and op_type in (exp.Except, exp.Intersect) 1366 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1367 ): 1368 self.unsupported(f"{op_name} ALL is not supported") 1369 1370 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1371 1372 if distinct is None: 1373 distinct = default_distinct 1374 if distinct is None: 1375 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1376 1377 if distinct is default_distinct: 1378 kind = "" 1379 else: 1380 kind = " DISTINCT" if distinct else " ALL" 1381 1382 by_name = " BY NAME" if expression.args.get("by_name") else "" 1383 return f"{op_name}{kind}{by_name}" 1384 1385 def set_operations(self, expression: exp.SetOperation) -> str: 1386 if not self.SET_OP_MODIFIERS: 1387 limit = expression.args.get("limit") 1388 order = expression.args.get("order") 1389 1390 if limit or order: 1391 select = self._move_ctes_to_top_level( 1392 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1393 ) 1394 1395 if limit: 1396 select = select.limit(limit.pop(), copy=False) 1397 if order: 1398 select = select.order_by(order.pop(), copy=False) 1399 return self.sql(select) 1400 1401 sqls: t.List[str] = [] 1402 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1403 1404 while stack: 1405 node = stack.pop() 1406 1407 if isinstance(node, exp.SetOperation): 1408 stack.append(node.expression) 1409 stack.append( 1410 self.maybe_comment( 1411 self.set_operation(node), comments=node.comments, separated=True 1412 ) 1413 ) 1414 stack.append(node.this) 1415 else: 1416 sqls.append(self.sql(node)) 1417 1418 this = self.sep().join(sqls) 1419 this = self.query_modifiers(expression, this) 1420 return self.prepend_ctes(expression, this) 1421 1422 def fetch_sql(self, expression: exp.Fetch) -> str: 1423 direction = expression.args.get("direction") 1424 direction = f" {direction}" if direction else "" 1425 count = self.sql(expression, "count") 1426 count = f" {count}" if count else "" 1427 if expression.args.get("percent"): 1428 count = f"{count} PERCENT" 1429 with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY" 1430 return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}" 1431 1432 def filter_sql(self, expression: exp.Filter) -> str: 1433 if self.AGGREGATE_FILTER_SUPPORTED: 1434 this = self.sql(expression, "this") 1435 where = self.sql(expression, "expression").strip() 1436 return f"{this} FILTER({where})" 1437 1438 agg = expression.this 1439 agg_arg = agg.this 1440 cond = expression.expression.this 1441 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1442 return self.sql(agg) 1443 1444 def hint_sql(self, expression: exp.Hint) -> str: 1445 if not self.QUERY_HINTS: 1446 self.unsupported("Hints are not supported") 1447 return "" 1448 1449 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1450 1451 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1452 using = self.sql(expression, "using") 1453 using = f" USING {using}" if using else "" 1454 columns = self.expressions(expression, key="columns", flat=True) 1455 columns = f"({columns})" if columns else "" 1456 partition_by = self.expressions(expression, key="partition_by", flat=True) 1457 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1458 where = self.sql(expression, "where") 1459 include = self.expressions(expression, key="include", flat=True) 1460 if include: 1461 include = f" INCLUDE ({include})" 1462 with_storage = self.expressions(expression, key="with_storage", flat=True) 1463 with_storage = f" WITH ({with_storage})" if with_storage else "" 1464 tablespace = self.sql(expression, "tablespace") 1465 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1466 on = self.sql(expression, "on") 1467 on = f" ON {on}" if on else "" 1468 1469 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1470 1471 def index_sql(self, expression: exp.Index) -> str: 1472 unique = "UNIQUE " if expression.args.get("unique") else "" 1473 primary = "PRIMARY " if expression.args.get("primary") else "" 1474 amp = "AMP " if expression.args.get("amp") else "" 1475 name = self.sql(expression, "this") 1476 name = f"{name} " if name else "" 1477 table = self.sql(expression, "table") 1478 table = f"{self.INDEX_ON} {table}" if table else "" 1479 1480 index = "INDEX " if not table else "" 1481 1482 params = self.sql(expression, "params") 1483 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1484 1485 def identifier_sql(self, expression: exp.Identifier) -> str: 1486 text = expression.name 1487 lower = text.lower() 1488 text = lower if self.normalize and not expression.quoted else text 1489 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1490 if ( 1491 expression.quoted 1492 or self.dialect.can_identify(text, self.identify) 1493 or lower in self.RESERVED_KEYWORDS 1494 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1495 ): 1496 text = f"{self._identifier_start}{text}{self._identifier_end}" 1497 return text 1498 1499 def hex_sql(self, expression: exp.Hex) -> str: 1500 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1501 if self.dialect.HEX_LOWERCASE: 1502 text = self.func("LOWER", text) 1503 1504 return text 1505 1506 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1507 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1508 if not self.dialect.HEX_LOWERCASE: 1509 text = self.func("LOWER", text) 1510 return text 1511 1512 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1513 input_format = self.sql(expression, "input_format") 1514 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1515 output_format = self.sql(expression, "output_format") 1516 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1517 return self.sep().join((input_format, output_format)) 1518 1519 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1520 string = self.sql(exp.Literal.string(expression.name)) 1521 return f"{prefix}{string}" 1522 1523 def partition_sql(self, expression: exp.Partition) -> str: 1524 return f"PARTITION({self.expressions(expression, flat=True)})" 1525 1526 def properties_sql(self, expression: exp.Properties) -> str: 1527 root_properties = [] 1528 with_properties = [] 1529 1530 for p in expression.expressions: 1531 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1532 if p_loc == exp.Properties.Location.POST_WITH: 1533 with_properties.append(p) 1534 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1535 root_properties.append(p) 1536 1537 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1538 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1539 1540 if root_props and with_props and not self.pretty: 1541 with_props = " " + with_props 1542 1543 return root_props + with_props 1544 1545 def root_properties(self, properties: exp.Properties) -> str: 1546 if properties.expressions: 1547 return self.expressions(properties, indent=False, sep=" ") 1548 return "" 1549 1550 def properties( 1551 self, 1552 properties: exp.Properties, 1553 prefix: str = "", 1554 sep: str = ", ", 1555 suffix: str = "", 1556 wrapped: bool = True, 1557 ) -> str: 1558 if properties.expressions: 1559 expressions = self.expressions(properties, sep=sep, indent=False) 1560 if expressions: 1561 expressions = self.wrap(expressions) if wrapped else expressions 1562 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1563 return "" 1564 1565 def with_properties(self, properties: exp.Properties) -> str: 1566 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1567 1568 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1569 properties_locs = defaultdict(list) 1570 for p in properties.expressions: 1571 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1572 if p_loc != exp.Properties.Location.UNSUPPORTED: 1573 properties_locs[p_loc].append(p) 1574 else: 1575 self.unsupported(f"Unsupported property {p.key}") 1576 1577 return properties_locs 1578 1579 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1580 if isinstance(expression.this, exp.Dot): 1581 return self.sql(expression, "this") 1582 return f"'{expression.name}'" if string_key else expression.name 1583 1584 def property_sql(self, expression: exp.Property) -> str: 1585 property_cls = expression.__class__ 1586 if property_cls == exp.Property: 1587 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1588 1589 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1590 if not property_name: 1591 self.unsupported(f"Unsupported property {expression.key}") 1592 1593 return f"{property_name}={self.sql(expression, 'this')}" 1594 1595 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1596 if self.SUPPORTS_CREATE_TABLE_LIKE: 1597 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1598 options = f" {options}" if options else "" 1599 1600 like = f"LIKE {self.sql(expression, 'this')}{options}" 1601 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1602 like = f"({like})" 1603 1604 return like 1605 1606 if expression.expressions: 1607 self.unsupported("Transpilation of LIKE property options is unsupported") 1608 1609 select = exp.select("*").from_(expression.this).limit(0) 1610 return f"AS {self.sql(select)}" 1611 1612 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1613 no = "NO " if expression.args.get("no") else "" 1614 protection = " PROTECTION" if expression.args.get("protection") else "" 1615 return f"{no}FALLBACK{protection}" 1616 1617 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1618 no = "NO " if expression.args.get("no") else "" 1619 local = expression.args.get("local") 1620 local = f"{local} " if local else "" 1621 dual = "DUAL " if expression.args.get("dual") else "" 1622 before = "BEFORE " if expression.args.get("before") else "" 1623 after = "AFTER " if expression.args.get("after") else "" 1624 return f"{no}{local}{dual}{before}{after}JOURNAL" 1625 1626 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1627 freespace = self.sql(expression, "this") 1628 percent = " PERCENT" if expression.args.get("percent") else "" 1629 return f"FREESPACE={freespace}{percent}" 1630 1631 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1632 if expression.args.get("default"): 1633 property = "DEFAULT" 1634 elif expression.args.get("on"): 1635 property = "ON" 1636 else: 1637 property = "OFF" 1638 return f"CHECKSUM={property}" 1639 1640 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1641 if expression.args.get("no"): 1642 return "NO MERGEBLOCKRATIO" 1643 if expression.args.get("default"): 1644 return "DEFAULT MERGEBLOCKRATIO" 1645 1646 percent = " PERCENT" if expression.args.get("percent") else "" 1647 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1648 1649 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1650 default = expression.args.get("default") 1651 minimum = expression.args.get("minimum") 1652 maximum = expression.args.get("maximum") 1653 if default or minimum or maximum: 1654 if default: 1655 prop = "DEFAULT" 1656 elif minimum: 1657 prop = "MINIMUM" 1658 else: 1659 prop = "MAXIMUM" 1660 return f"{prop} DATABLOCKSIZE" 1661 units = expression.args.get("units") 1662 units = f" {units}" if units else "" 1663 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1664 1665 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1666 autotemp = expression.args.get("autotemp") 1667 always = expression.args.get("always") 1668 default = expression.args.get("default") 1669 manual = expression.args.get("manual") 1670 never = expression.args.get("never") 1671 1672 if autotemp is not None: 1673 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1674 elif always: 1675 prop = "ALWAYS" 1676 elif default: 1677 prop = "DEFAULT" 1678 elif manual: 1679 prop = "MANUAL" 1680 elif never: 1681 prop = "NEVER" 1682 return f"BLOCKCOMPRESSION={prop}" 1683 1684 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1685 no = expression.args.get("no") 1686 no = " NO" if no else "" 1687 concurrent = expression.args.get("concurrent") 1688 concurrent = " CONCURRENT" if concurrent else "" 1689 target = self.sql(expression, "target") 1690 target = f" {target}" if target else "" 1691 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1692 1693 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1694 if isinstance(expression.this, list): 1695 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1696 if expression.this: 1697 modulus = self.sql(expression, "this") 1698 remainder = self.sql(expression, "expression") 1699 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1700 1701 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1702 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1703 return f"FROM ({from_expressions}) TO ({to_expressions})" 1704 1705 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1706 this = self.sql(expression, "this") 1707 1708 for_values_or_default = expression.expression 1709 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1710 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1711 else: 1712 for_values_or_default = " DEFAULT" 1713 1714 return f"PARTITION OF {this}{for_values_or_default}" 1715 1716 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1717 kind = expression.args.get("kind") 1718 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1719 for_or_in = expression.args.get("for_or_in") 1720 for_or_in = f" {for_or_in}" if for_or_in else "" 1721 lock_type = expression.args.get("lock_type") 1722 override = " OVERRIDE" if expression.args.get("override") else "" 1723 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1724 1725 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1726 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1727 statistics = expression.args.get("statistics") 1728 statistics_sql = "" 1729 if statistics is not None: 1730 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1731 return f"{data_sql}{statistics_sql}" 1732 1733 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1734 this = self.sql(expression, "this") 1735 this = f"HISTORY_TABLE={this}" if this else "" 1736 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1737 data_consistency = ( 1738 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1739 ) 1740 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1741 retention_period = ( 1742 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1743 ) 1744 1745 if this: 1746 on_sql = self.func("ON", this, data_consistency, retention_period) 1747 else: 1748 on_sql = "ON" if expression.args.get("on") else "OFF" 1749 1750 sql = f"SYSTEM_VERSIONING={on_sql}" 1751 1752 return f"WITH({sql})" if expression.args.get("with") else sql 1753 1754 def insert_sql(self, expression: exp.Insert) -> str: 1755 hint = self.sql(expression, "hint") 1756 overwrite = expression.args.get("overwrite") 1757 1758 if isinstance(expression.this, exp.Directory): 1759 this = " OVERWRITE" if overwrite else " INTO" 1760 else: 1761 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1762 1763 stored = self.sql(expression, "stored") 1764 stored = f" {stored}" if stored else "" 1765 alternative = expression.args.get("alternative") 1766 alternative = f" OR {alternative}" if alternative else "" 1767 ignore = " IGNORE" if expression.args.get("ignore") else "" 1768 is_function = expression.args.get("is_function") 1769 if is_function: 1770 this = f"{this} FUNCTION" 1771 this = f"{this} {self.sql(expression, 'this')}" 1772 1773 exists = " IF EXISTS" if expression.args.get("exists") else "" 1774 where = self.sql(expression, "where") 1775 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1776 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1777 on_conflict = self.sql(expression, "conflict") 1778 on_conflict = f" {on_conflict}" if on_conflict else "" 1779 by_name = " BY NAME" if expression.args.get("by_name") else "" 1780 returning = self.sql(expression, "returning") 1781 1782 if self.RETURNING_END: 1783 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1784 else: 1785 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1786 1787 partition_by = self.sql(expression, "partition") 1788 partition_by = f" {partition_by}" if partition_by else "" 1789 settings = self.sql(expression, "settings") 1790 settings = f" {settings}" if settings else "" 1791 1792 source = self.sql(expression, "source") 1793 source = f"TABLE {source}" if source else "" 1794 1795 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1796 return self.prepend_ctes(expression, sql) 1797 1798 def introducer_sql(self, expression: exp.Introducer) -> str: 1799 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1800 1801 def kill_sql(self, expression: exp.Kill) -> str: 1802 kind = self.sql(expression, "kind") 1803 kind = f" {kind}" if kind else "" 1804 this = self.sql(expression, "this") 1805 this = f" {this}" if this else "" 1806 return f"KILL{kind}{this}" 1807 1808 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1809 return expression.name 1810 1811 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1812 return expression.name 1813 1814 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1815 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1816 1817 constraint = self.sql(expression, "constraint") 1818 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1819 1820 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1821 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1822 action = self.sql(expression, "action") 1823 1824 expressions = self.expressions(expression, flat=True) 1825 if expressions: 1826 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1827 expressions = f" {set_keyword}{expressions}" 1828 1829 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}" 1830 1831 def returning_sql(self, expression: exp.Returning) -> str: 1832 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1833 1834 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1835 fields = self.sql(expression, "fields") 1836 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1837 escaped = self.sql(expression, "escaped") 1838 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1839 items = self.sql(expression, "collection_items") 1840 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1841 keys = self.sql(expression, "map_keys") 1842 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1843 lines = self.sql(expression, "lines") 1844 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1845 null = self.sql(expression, "null") 1846 null = f" NULL DEFINED AS {null}" if null else "" 1847 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1848 1849 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1850 return f"WITH ({self.expressions(expression, flat=True)})" 1851 1852 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1853 this = f"{self.sql(expression, 'this')} INDEX" 1854 target = self.sql(expression, "target") 1855 target = f" FOR {target}" if target else "" 1856 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1857 1858 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1859 this = self.sql(expression, "this") 1860 kind = self.sql(expression, "kind") 1861 expr = self.sql(expression, "expression") 1862 return f"{this} ({kind} => {expr})" 1863 1864 def table_parts(self, expression: exp.Table) -> str: 1865 return ".".join( 1866 self.sql(part) 1867 for part in ( 1868 expression.args.get("catalog"), 1869 expression.args.get("db"), 1870 expression.args.get("this"), 1871 ) 1872 if part is not None 1873 ) 1874 1875 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1876 table = self.table_parts(expression) 1877 only = "ONLY " if expression.args.get("only") else "" 1878 partition = self.sql(expression, "partition") 1879 partition = f" {partition}" if partition else "" 1880 version = self.sql(expression, "version") 1881 version = f" {version}" if version else "" 1882 alias = self.sql(expression, "alias") 1883 alias = f"{sep}{alias}" if alias else "" 1884 1885 sample = self.sql(expression, "sample") 1886 if self.dialect.ALIAS_POST_TABLESAMPLE: 1887 sample_pre_alias = sample 1888 sample_post_alias = "" 1889 else: 1890 sample_pre_alias = "" 1891 sample_post_alias = sample 1892 1893 hints = self.expressions(expression, key="hints", sep=" ") 1894 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1895 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1896 joins = self.indent( 1897 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1898 ) 1899 laterals = self.expressions(expression, key="laterals", sep="") 1900 1901 file_format = self.sql(expression, "format") 1902 if file_format: 1903 pattern = self.sql(expression, "pattern") 1904 pattern = f", PATTERN => {pattern}" if pattern else "" 1905 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1906 1907 ordinality = expression.args.get("ordinality") or "" 1908 if ordinality: 1909 ordinality = f" WITH ORDINALITY{alias}" 1910 alias = "" 1911 1912 when = self.sql(expression, "when") 1913 if when: 1914 table = f"{table} {when}" 1915 1916 changes = self.sql(expression, "changes") 1917 changes = f" {changes}" if changes else "" 1918 1919 rows_from = self.expressions(expression, key="rows_from") 1920 if rows_from: 1921 table = f"ROWS FROM {self.wrap(rows_from)}" 1922 1923 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 1924 1925 def tablesample_sql( 1926 self, 1927 expression: exp.TableSample, 1928 tablesample_keyword: t.Optional[str] = None, 1929 ) -> str: 1930 method = self.sql(expression, "method") 1931 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 1932 numerator = self.sql(expression, "bucket_numerator") 1933 denominator = self.sql(expression, "bucket_denominator") 1934 field = self.sql(expression, "bucket_field") 1935 field = f" ON {field}" if field else "" 1936 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 1937 seed = self.sql(expression, "seed") 1938 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 1939 1940 size = self.sql(expression, "size") 1941 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 1942 size = f"{size} ROWS" 1943 1944 percent = self.sql(expression, "percent") 1945 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 1946 percent = f"{percent} PERCENT" 1947 1948 expr = f"{bucket}{percent}{size}" 1949 if self.TABLESAMPLE_REQUIRES_PARENS: 1950 expr = f"({expr})" 1951 1952 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 1953 1954 def pivot_sql(self, expression: exp.Pivot) -> str: 1955 expressions = self.expressions(expression, flat=True) 1956 1957 if expression.this: 1958 this = self.sql(expression, "this") 1959 if not expressions: 1960 return f"UNPIVOT {this}" 1961 1962 on = f"{self.seg('ON')} {expressions}" 1963 using = self.expressions(expression, key="using", flat=True) 1964 using = f"{self.seg('USING')} {using}" if using else "" 1965 group = self.sql(expression, "group") 1966 return f"PIVOT {this}{on}{using}{group}" 1967 1968 alias = self.sql(expression, "alias") 1969 alias = f" AS {alias}" if alias else "" 1970 direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT") 1971 1972 field = self.sql(expression, "field") 1973 1974 include_nulls = expression.args.get("include_nulls") 1975 if include_nulls is not None: 1976 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 1977 else: 1978 nulls = "" 1979 1980 default_on_null = self.sql(expression, "default_on_null") 1981 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 1982 return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 1983 1984 def version_sql(self, expression: exp.Version) -> str: 1985 this = f"FOR {expression.name}" 1986 kind = expression.text("kind") 1987 expr = self.sql(expression, "expression") 1988 return f"{this} {kind} {expr}" 1989 1990 def tuple_sql(self, expression: exp.Tuple) -> str: 1991 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 1992 1993 def update_sql(self, expression: exp.Update) -> str: 1994 this = self.sql(expression, "this") 1995 set_sql = self.expressions(expression, flat=True) 1996 from_sql = self.sql(expression, "from") 1997 where_sql = self.sql(expression, "where") 1998 returning = self.sql(expression, "returning") 1999 order = self.sql(expression, "order") 2000 limit = self.sql(expression, "limit") 2001 if self.RETURNING_END: 2002 expression_sql = f"{from_sql}{where_sql}{returning}" 2003 else: 2004 expression_sql = f"{returning}{from_sql}{where_sql}" 2005 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2006 return self.prepend_ctes(expression, sql) 2007 2008 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2009 values_as_table = values_as_table and self.VALUES_AS_TABLE 2010 2011 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2012 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2013 args = self.expressions(expression) 2014 alias = self.sql(expression, "alias") 2015 values = f"VALUES{self.seg('')}{args}" 2016 values = ( 2017 f"({values})" 2018 if self.WRAP_DERIVED_VALUES 2019 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2020 else values 2021 ) 2022 return f"{values} AS {alias}" if alias else values 2023 2024 # Converts `VALUES...` expression into a series of select unions. 2025 alias_node = expression.args.get("alias") 2026 column_names = alias_node and alias_node.columns 2027 2028 selects: t.List[exp.Query] = [] 2029 2030 for i, tup in enumerate(expression.expressions): 2031 row = tup.expressions 2032 2033 if i == 0 and column_names: 2034 row = [ 2035 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2036 ] 2037 2038 selects.append(exp.Select(expressions=row)) 2039 2040 if self.pretty: 2041 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2042 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2043 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2044 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2045 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2046 2047 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2048 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2049 return f"({unions}){alias}" 2050 2051 def var_sql(self, expression: exp.Var) -> str: 2052 return self.sql(expression, "this") 2053 2054 @unsupported_args("expressions") 2055 def into_sql(self, expression: exp.Into) -> str: 2056 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2057 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2058 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2059 2060 def from_sql(self, expression: exp.From) -> str: 2061 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2062 2063 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2064 grouping_sets = self.expressions(expression, indent=False) 2065 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2066 2067 def rollup_sql(self, expression: exp.Rollup) -> str: 2068 expressions = self.expressions(expression, indent=False) 2069 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2070 2071 def cube_sql(self, expression: exp.Cube) -> str: 2072 expressions = self.expressions(expression, indent=False) 2073 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2074 2075 def group_sql(self, expression: exp.Group) -> str: 2076 group_by_all = expression.args.get("all") 2077 if group_by_all is True: 2078 modifier = " ALL" 2079 elif group_by_all is False: 2080 modifier = " DISTINCT" 2081 else: 2082 modifier = "" 2083 2084 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2085 2086 grouping_sets = self.expressions(expression, key="grouping_sets") 2087 cube = self.expressions(expression, key="cube") 2088 rollup = self.expressions(expression, key="rollup") 2089 2090 groupings = csv( 2091 self.seg(grouping_sets) if grouping_sets else "", 2092 self.seg(cube) if cube else "", 2093 self.seg(rollup) if rollup else "", 2094 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2095 sep=self.GROUPINGS_SEP, 2096 ) 2097 2098 if ( 2099 expression.expressions 2100 and groupings 2101 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2102 ): 2103 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2104 2105 return f"{group_by}{groupings}" 2106 2107 def having_sql(self, expression: exp.Having) -> str: 2108 this = self.indent(self.sql(expression, "this")) 2109 return f"{self.seg('HAVING')}{self.sep()}{this}" 2110 2111 def connect_sql(self, expression: exp.Connect) -> str: 2112 start = self.sql(expression, "start") 2113 start = self.seg(f"START WITH {start}") if start else "" 2114 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2115 connect = self.sql(expression, "connect") 2116 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2117 return start + connect 2118 2119 def prior_sql(self, expression: exp.Prior) -> str: 2120 return f"PRIOR {self.sql(expression, 'this')}" 2121 2122 def join_sql(self, expression: exp.Join) -> str: 2123 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2124 side = None 2125 else: 2126 side = expression.side 2127 2128 op_sql = " ".join( 2129 op 2130 for op in ( 2131 expression.method, 2132 "GLOBAL" if expression.args.get("global") else None, 2133 side, 2134 expression.kind, 2135 expression.hint if self.JOIN_HINTS else None, 2136 ) 2137 if op 2138 ) 2139 match_cond = self.sql(expression, "match_condition") 2140 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2141 on_sql = self.sql(expression, "on") 2142 using = expression.args.get("using") 2143 2144 if not on_sql and using: 2145 on_sql = csv(*(self.sql(column) for column in using)) 2146 2147 this = expression.this 2148 this_sql = self.sql(this) 2149 2150 exprs = self.expressions(expression) 2151 if exprs: 2152 this_sql = f"{this_sql},{self.seg(exprs)}" 2153 2154 if on_sql: 2155 on_sql = self.indent(on_sql, skip_first=True) 2156 space = self.seg(" " * self.pad) if self.pretty else " " 2157 if using: 2158 on_sql = f"{space}USING ({on_sql})" 2159 else: 2160 on_sql = f"{space}ON {on_sql}" 2161 elif not op_sql: 2162 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2163 return f" {this_sql}" 2164 2165 return f", {this_sql}" 2166 2167 if op_sql != "STRAIGHT_JOIN": 2168 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2169 2170 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2171 2172 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2173 args = self.expressions(expression, flat=True) 2174 args = f"({args})" if len(args.split(",")) > 1 else args 2175 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2176 2177 def lateral_op(self, expression: exp.Lateral) -> str: 2178 cross_apply = expression.args.get("cross_apply") 2179 2180 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2181 if cross_apply is True: 2182 op = "INNER JOIN " 2183 elif cross_apply is False: 2184 op = "LEFT JOIN " 2185 else: 2186 op = "" 2187 2188 return f"{op}LATERAL" 2189 2190 def lateral_sql(self, expression: exp.Lateral) -> str: 2191 this = self.sql(expression, "this") 2192 2193 if expression.args.get("view"): 2194 alias = expression.args["alias"] 2195 columns = self.expressions(alias, key="columns", flat=True) 2196 table = f" {alias.name}" if alias.name else "" 2197 columns = f" AS {columns}" if columns else "" 2198 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2199 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2200 2201 alias = self.sql(expression, "alias") 2202 alias = f" AS {alias}" if alias else "" 2203 return f"{self.lateral_op(expression)} {this}{alias}" 2204 2205 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2206 this = self.sql(expression, "this") 2207 2208 args = [ 2209 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2210 for e in (expression.args.get(k) for k in ("offset", "expression")) 2211 if e 2212 ] 2213 2214 args_sql = ", ".join(self.sql(e) for e in args) 2215 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2216 expressions = self.expressions(expression, flat=True) 2217 expressions = f" BY {expressions}" if expressions else "" 2218 2219 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}" 2220 2221 def offset_sql(self, expression: exp.Offset) -> str: 2222 this = self.sql(expression, "this") 2223 value = expression.expression 2224 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2225 expressions = self.expressions(expression, flat=True) 2226 expressions = f" BY {expressions}" if expressions else "" 2227 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2228 2229 def setitem_sql(self, expression: exp.SetItem) -> str: 2230 kind = self.sql(expression, "kind") 2231 kind = f"{kind} " if kind else "" 2232 this = self.sql(expression, "this") 2233 expressions = self.expressions(expression) 2234 collate = self.sql(expression, "collate") 2235 collate = f" COLLATE {collate}" if collate else "" 2236 global_ = "GLOBAL " if expression.args.get("global") else "" 2237 return f"{global_}{kind}{this}{expressions}{collate}" 2238 2239 def set_sql(self, expression: exp.Set) -> str: 2240 expressions = ( 2241 f" {self.expressions(expression, flat=True)}" if expression.expressions else "" 2242 ) 2243 tag = " TAG" if expression.args.get("tag") else "" 2244 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2245 2246 def pragma_sql(self, expression: exp.Pragma) -> str: 2247 return f"PRAGMA {self.sql(expression, 'this')}" 2248 2249 def lock_sql(self, expression: exp.Lock) -> str: 2250 if not self.LOCKING_READS_SUPPORTED: 2251 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2252 return "" 2253 2254 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2255 expressions = self.expressions(expression, flat=True) 2256 expressions = f" OF {expressions}" if expressions else "" 2257 wait = expression.args.get("wait") 2258 2259 if wait is not None: 2260 if isinstance(wait, exp.Literal): 2261 wait = f" WAIT {self.sql(wait)}" 2262 else: 2263 wait = " NOWAIT" if wait else " SKIP LOCKED" 2264 2265 return f"{lock_type}{expressions}{wait or ''}" 2266 2267 def literal_sql(self, expression: exp.Literal) -> str: 2268 text = expression.this or "" 2269 if expression.is_string: 2270 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2271 return text 2272 2273 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2274 if self.dialect.ESCAPED_SEQUENCES: 2275 to_escaped = self.dialect.ESCAPED_SEQUENCES 2276 text = "".join( 2277 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2278 ) 2279 2280 return self._replace_line_breaks(text).replace( 2281 self.dialect.QUOTE_END, self._escaped_quote_end 2282 ) 2283 2284 def loaddata_sql(self, expression: exp.LoadData) -> str: 2285 local = " LOCAL" if expression.args.get("local") else "" 2286 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2287 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2288 this = f" INTO TABLE {self.sql(expression, 'this')}" 2289 partition = self.sql(expression, "partition") 2290 partition = f" {partition}" if partition else "" 2291 input_format = self.sql(expression, "input_format") 2292 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2293 serde = self.sql(expression, "serde") 2294 serde = f" SERDE {serde}" if serde else "" 2295 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2296 2297 def null_sql(self, *_) -> str: 2298 return "NULL" 2299 2300 def boolean_sql(self, expression: exp.Boolean) -> str: 2301 return "TRUE" if expression.this else "FALSE" 2302 2303 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2304 this = self.sql(expression, "this") 2305 this = f"{this} " if this else this 2306 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2307 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2308 2309 def withfill_sql(self, expression: exp.WithFill) -> str: 2310 from_sql = self.sql(expression, "from") 2311 from_sql = f" FROM {from_sql}" if from_sql else "" 2312 to_sql = self.sql(expression, "to") 2313 to_sql = f" TO {to_sql}" if to_sql else "" 2314 step_sql = self.sql(expression, "step") 2315 step_sql = f" STEP {step_sql}" if step_sql else "" 2316 interpolated_values = [ 2317 f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}" 2318 for named_expression in expression.args.get("interpolate") or [] 2319 ] 2320 interpolate = ( 2321 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2322 ) 2323 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2324 2325 def cluster_sql(self, expression: exp.Cluster) -> str: 2326 return self.op_expressions("CLUSTER BY", expression) 2327 2328 def distribute_sql(self, expression: exp.Distribute) -> str: 2329 return self.op_expressions("DISTRIBUTE BY", expression) 2330 2331 def sort_sql(self, expression: exp.Sort) -> str: 2332 return self.op_expressions("SORT BY", expression) 2333 2334 def ordered_sql(self, expression: exp.Ordered) -> str: 2335 desc = expression.args.get("desc") 2336 asc = not desc 2337 2338 nulls_first = expression.args.get("nulls_first") 2339 nulls_last = not nulls_first 2340 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2341 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2342 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2343 2344 this = self.sql(expression, "this") 2345 2346 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2347 nulls_sort_change = "" 2348 if nulls_first and ( 2349 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2350 ): 2351 nulls_sort_change = " NULLS FIRST" 2352 elif ( 2353 nulls_last 2354 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2355 and not nulls_are_last 2356 ): 2357 nulls_sort_change = " NULLS LAST" 2358 2359 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2360 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2361 window = expression.find_ancestor(exp.Window, exp.Select) 2362 if isinstance(window, exp.Window) and window.args.get("spec"): 2363 self.unsupported( 2364 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2365 ) 2366 nulls_sort_change = "" 2367 elif ( 2368 self.NULL_ORDERING_SUPPORTED is False 2369 and (isinstance(expression.find_ancestor(exp.AggFunc, exp.Select), exp.AggFunc)) 2370 and ( 2371 (asc and nulls_sort_change == " NULLS LAST") 2372 or (desc and nulls_sort_change == " NULLS FIRST") 2373 ) 2374 ): 2375 self.unsupported( 2376 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2377 ) 2378 nulls_sort_change = "" 2379 elif self.NULL_ORDERING_SUPPORTED is None: 2380 if expression.this.is_int: 2381 self.unsupported( 2382 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2383 ) 2384 elif not isinstance(expression.this, exp.Rand): 2385 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2386 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2387 nulls_sort_change = "" 2388 2389 with_fill = self.sql(expression, "with_fill") 2390 with_fill = f" {with_fill}" if with_fill else "" 2391 2392 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2393 2394 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2395 window_frame = self.sql(expression, "window_frame") 2396 window_frame = f"{window_frame} " if window_frame else "" 2397 2398 this = self.sql(expression, "this") 2399 2400 return f"{window_frame}{this}" 2401 2402 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2403 partition = self.partition_by_sql(expression) 2404 order = self.sql(expression, "order") 2405 measures = self.expressions(expression, key="measures") 2406 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2407 rows = self.sql(expression, "rows") 2408 rows = self.seg(rows) if rows else "" 2409 after = self.sql(expression, "after") 2410 after = self.seg(after) if after else "" 2411 pattern = self.sql(expression, "pattern") 2412 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2413 definition_sqls = [ 2414 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2415 for definition in expression.args.get("define", []) 2416 ] 2417 definitions = self.expressions(sqls=definition_sqls) 2418 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2419 body = "".join( 2420 ( 2421 partition, 2422 order, 2423 measures, 2424 rows, 2425 after, 2426 pattern, 2427 define, 2428 ) 2429 ) 2430 alias = self.sql(expression, "alias") 2431 alias = f" {alias}" if alias else "" 2432 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2433 2434 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2435 limit = expression.args.get("limit") 2436 2437 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2438 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2439 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2440 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2441 2442 return csv( 2443 *sqls, 2444 *[self.sql(join) for join in expression.args.get("joins") or []], 2445 self.sql(expression, "connect"), 2446 self.sql(expression, "match"), 2447 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2448 self.sql(expression, "prewhere"), 2449 self.sql(expression, "where"), 2450 self.sql(expression, "group"), 2451 self.sql(expression, "having"), 2452 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2453 self.sql(expression, "order"), 2454 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2455 *self.after_limit_modifiers(expression), 2456 self.options_modifier(expression), 2457 sep="", 2458 ) 2459 2460 def options_modifier(self, expression: exp.Expression) -> str: 2461 options = self.expressions(expression, key="options") 2462 return f" {options}" if options else "" 2463 2464 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2465 return "" 2466 2467 def offset_limit_modifiers( 2468 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2469 ) -> t.List[str]: 2470 return [ 2471 self.sql(expression, "offset") if fetch else self.sql(limit), 2472 self.sql(limit) if fetch else self.sql(expression, "offset"), 2473 ] 2474 2475 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2476 locks = self.expressions(expression, key="locks", sep=" ") 2477 locks = f" {locks}" if locks else "" 2478 return [locks, self.sql(expression, "sample")] 2479 2480 def select_sql(self, expression: exp.Select) -> str: 2481 into = expression.args.get("into") 2482 if not self.SUPPORTS_SELECT_INTO and into: 2483 into.pop() 2484 2485 hint = self.sql(expression, "hint") 2486 distinct = self.sql(expression, "distinct") 2487 distinct = f" {distinct}" if distinct else "" 2488 kind = self.sql(expression, "kind") 2489 2490 limit = expression.args.get("limit") 2491 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2492 top = self.limit_sql(limit, top=True) 2493 limit.pop() 2494 else: 2495 top = "" 2496 2497 expressions = self.expressions(expression) 2498 2499 if kind: 2500 if kind in self.SELECT_KINDS: 2501 kind = f" AS {kind}" 2502 else: 2503 if kind == "STRUCT": 2504 expressions = self.expressions( 2505 sqls=[ 2506 self.sql( 2507 exp.Struct( 2508 expressions=[ 2509 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2510 if isinstance(e, exp.Alias) 2511 else e 2512 for e in expression.expressions 2513 ] 2514 ) 2515 ) 2516 ] 2517 ) 2518 kind = "" 2519 2520 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2521 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2522 2523 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2524 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2525 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2526 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2527 sql = self.query_modifiers( 2528 expression, 2529 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2530 self.sql(expression, "into", comment=False), 2531 self.sql(expression, "from", comment=False), 2532 ) 2533 2534 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2535 if expression.args.get("with"): 2536 sql = self.maybe_comment(sql, expression) 2537 expression.pop_comments() 2538 2539 sql = self.prepend_ctes(expression, sql) 2540 2541 if not self.SUPPORTS_SELECT_INTO and into: 2542 if into.args.get("temporary"): 2543 table_kind = " TEMPORARY" 2544 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2545 table_kind = " UNLOGGED" 2546 else: 2547 table_kind = "" 2548 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2549 2550 return sql 2551 2552 def schema_sql(self, expression: exp.Schema) -> str: 2553 this = self.sql(expression, "this") 2554 sql = self.schema_columns_sql(expression) 2555 return f"{this} {sql}" if this and sql else this or sql 2556 2557 def schema_columns_sql(self, expression: exp.Schema) -> str: 2558 if expression.expressions: 2559 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2560 return "" 2561 2562 def star_sql(self, expression: exp.Star) -> str: 2563 except_ = self.expressions(expression, key="except", flat=True) 2564 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2565 replace = self.expressions(expression, key="replace", flat=True) 2566 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2567 rename = self.expressions(expression, key="rename", flat=True) 2568 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2569 return f"*{except_}{replace}{rename}" 2570 2571 def parameter_sql(self, expression: exp.Parameter) -> str: 2572 this = self.sql(expression, "this") 2573 return f"{self.PARAMETER_TOKEN}{this}" 2574 2575 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2576 this = self.sql(expression, "this") 2577 kind = expression.text("kind") 2578 if kind: 2579 kind = f"{kind}." 2580 return f"@@{kind}{this}" 2581 2582 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2583 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2584 2585 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2586 alias = self.sql(expression, "alias") 2587 alias = f"{sep}{alias}" if alias else "" 2588 sample = self.sql(expression, "sample") 2589 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2590 alias = f"{sample}{alias}" 2591 2592 # Set to None so it's not generated again by self.query_modifiers() 2593 expression.set("sample", None) 2594 2595 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2596 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2597 return self.prepend_ctes(expression, sql) 2598 2599 def qualify_sql(self, expression: exp.Qualify) -> str: 2600 this = self.indent(self.sql(expression, "this")) 2601 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2602 2603 def unnest_sql(self, expression: exp.Unnest) -> str: 2604 args = self.expressions(expression, flat=True) 2605 2606 alias = expression.args.get("alias") 2607 offset = expression.args.get("offset") 2608 2609 if self.UNNEST_WITH_ORDINALITY: 2610 if alias and isinstance(offset, exp.Expression): 2611 alias.append("columns", offset) 2612 2613 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2614 columns = alias.columns 2615 alias = self.sql(columns[0]) if columns else "" 2616 else: 2617 alias = self.sql(alias) 2618 2619 alias = f" AS {alias}" if alias else alias 2620 if self.UNNEST_WITH_ORDINALITY: 2621 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2622 else: 2623 if isinstance(offset, exp.Expression): 2624 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2625 elif offset: 2626 suffix = f"{alias} WITH OFFSET" 2627 else: 2628 suffix = alias 2629 2630 return f"UNNEST({args}){suffix}" 2631 2632 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2633 return "" 2634 2635 def where_sql(self, expression: exp.Where) -> str: 2636 this = self.indent(self.sql(expression, "this")) 2637 return f"{self.seg('WHERE')}{self.sep()}{this}" 2638 2639 def window_sql(self, expression: exp.Window) -> str: 2640 this = self.sql(expression, "this") 2641 partition = self.partition_by_sql(expression) 2642 order = expression.args.get("order") 2643 order = self.order_sql(order, flat=True) if order else "" 2644 spec = self.sql(expression, "spec") 2645 alias = self.sql(expression, "alias") 2646 over = self.sql(expression, "over") or "OVER" 2647 2648 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2649 2650 first = expression.args.get("first") 2651 if first is None: 2652 first = "" 2653 else: 2654 first = "FIRST" if first else "LAST" 2655 2656 if not partition and not order and not spec and alias: 2657 return f"{this} {alias}" 2658 2659 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2660 return f"{this} ({args})" 2661 2662 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2663 partition = self.expressions(expression, key="partition_by", flat=True) 2664 return f"PARTITION BY {partition}" if partition else "" 2665 2666 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2667 kind = self.sql(expression, "kind") 2668 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2669 end = ( 2670 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2671 or "CURRENT ROW" 2672 ) 2673 return f"{kind} BETWEEN {start} AND {end}" 2674 2675 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2676 this = self.sql(expression, "this") 2677 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2678 return f"{this} WITHIN GROUP ({expression_sql})" 2679 2680 def between_sql(self, expression: exp.Between) -> str: 2681 this = self.sql(expression, "this") 2682 low = self.sql(expression, "low") 2683 high = self.sql(expression, "high") 2684 return f"{this} BETWEEN {low} AND {high}" 2685 2686 def bracket_offset_expressions( 2687 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2688 ) -> t.List[exp.Expression]: 2689 return apply_index_offset( 2690 expression.this, 2691 expression.expressions, 2692 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2693 ) 2694 2695 def bracket_sql(self, expression: exp.Bracket) -> str: 2696 expressions = self.bracket_offset_expressions(expression) 2697 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2698 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2699 2700 def all_sql(self, expression: exp.All) -> str: 2701 return f"ALL {self.wrap(expression)}" 2702 2703 def any_sql(self, expression: exp.Any) -> str: 2704 this = self.sql(expression, "this") 2705 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2706 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2707 this = self.wrap(this) 2708 return f"ANY{this}" 2709 return f"ANY {this}" 2710 2711 def exists_sql(self, expression: exp.Exists) -> str: 2712 return f"EXISTS{self.wrap(expression)}" 2713 2714 def case_sql(self, expression: exp.Case) -> str: 2715 this = self.sql(expression, "this") 2716 statements = [f"CASE {this}" if this else "CASE"] 2717 2718 for e in expression.args["ifs"]: 2719 statements.append(f"WHEN {self.sql(e, 'this')}") 2720 statements.append(f"THEN {self.sql(e, 'true')}") 2721 2722 default = self.sql(expression, "default") 2723 2724 if default: 2725 statements.append(f"ELSE {default}") 2726 2727 statements.append("END") 2728 2729 if self.pretty and self.too_wide(statements): 2730 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2731 2732 return " ".join(statements) 2733 2734 def constraint_sql(self, expression: exp.Constraint) -> str: 2735 this = self.sql(expression, "this") 2736 expressions = self.expressions(expression, flat=True) 2737 return f"CONSTRAINT {this} {expressions}" 2738 2739 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2740 order = expression.args.get("order") 2741 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2742 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2743 2744 def extract_sql(self, expression: exp.Extract) -> str: 2745 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2746 expression_sql = self.sql(expression, "expression") 2747 return f"EXTRACT({this} FROM {expression_sql})" 2748 2749 def trim_sql(self, expression: exp.Trim) -> str: 2750 trim_type = self.sql(expression, "position") 2751 2752 if trim_type == "LEADING": 2753 func_name = "LTRIM" 2754 elif trim_type == "TRAILING": 2755 func_name = "RTRIM" 2756 else: 2757 func_name = "TRIM" 2758 2759 return self.func(func_name, expression.this, expression.expression) 2760 2761 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2762 args = expression.expressions 2763 if isinstance(expression, exp.ConcatWs): 2764 args = args[1:] # Skip the delimiter 2765 2766 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2767 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2768 2769 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2770 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2771 2772 return args 2773 2774 def concat_sql(self, expression: exp.Concat) -> str: 2775 expressions = self.convert_concat_args(expression) 2776 2777 # Some dialects don't allow a single-argument CONCAT call 2778 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2779 return self.sql(expressions[0]) 2780 2781 return self.func("CONCAT", *expressions) 2782 2783 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2784 return self.func( 2785 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2786 ) 2787 2788 def check_sql(self, expression: exp.Check) -> str: 2789 this = self.sql(expression, key="this") 2790 return f"CHECK ({this})" 2791 2792 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2793 expressions = self.expressions(expression, flat=True) 2794 reference = self.sql(expression, "reference") 2795 reference = f" {reference}" if reference else "" 2796 delete = self.sql(expression, "delete") 2797 delete = f" ON DELETE {delete}" if delete else "" 2798 update = self.sql(expression, "update") 2799 update = f" ON UPDATE {update}" if update else "" 2800 return f"FOREIGN KEY ({expressions}){reference}{delete}{update}" 2801 2802 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2803 expressions = self.expressions(expression, flat=True) 2804 options = self.expressions(expression, key="options", flat=True, sep=" ") 2805 options = f" {options}" if options else "" 2806 return f"PRIMARY KEY ({expressions}){options}" 2807 2808 def if_sql(self, expression: exp.If) -> str: 2809 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2810 2811 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2812 modifier = expression.args.get("modifier") 2813 modifier = f" {modifier}" if modifier else "" 2814 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2815 2816 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2817 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2818 2819 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2820 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2821 2822 if expression.args.get("escape"): 2823 path = self.escape_str(path) 2824 2825 if self.QUOTE_JSON_PATH: 2826 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2827 2828 return path 2829 2830 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2831 if isinstance(expression, exp.JSONPathPart): 2832 transform = self.TRANSFORMS.get(expression.__class__) 2833 if not callable(transform): 2834 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2835 return "" 2836 2837 return transform(self, expression) 2838 2839 if isinstance(expression, int): 2840 return str(expression) 2841 2842 if self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2843 escaped = expression.replace("'", "\\'") 2844 escaped = f"\\'{expression}\\'" 2845 else: 2846 escaped = expression.replace('"', '\\"') 2847 escaped = f'"{escaped}"' 2848 2849 return escaped 2850 2851 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2852 return f"{self.sql(expression, 'this')} FORMAT JSON" 2853 2854 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2855 null_handling = expression.args.get("null_handling") 2856 null_handling = f" {null_handling}" if null_handling else "" 2857 2858 unique_keys = expression.args.get("unique_keys") 2859 if unique_keys is not None: 2860 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2861 else: 2862 unique_keys = "" 2863 2864 return_type = self.sql(expression, "return_type") 2865 return_type = f" RETURNING {return_type}" if return_type else "" 2866 encoding = self.sql(expression, "encoding") 2867 encoding = f" ENCODING {encoding}" if encoding else "" 2868 2869 return self.func( 2870 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2871 *expression.expressions, 2872 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2873 ) 2874 2875 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2876 return self.jsonobject_sql(expression) 2877 2878 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2879 null_handling = expression.args.get("null_handling") 2880 null_handling = f" {null_handling}" if null_handling else "" 2881 return_type = self.sql(expression, "return_type") 2882 return_type = f" RETURNING {return_type}" if return_type else "" 2883 strict = " STRICT" if expression.args.get("strict") else "" 2884 return self.func( 2885 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2886 ) 2887 2888 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2889 this = self.sql(expression, "this") 2890 order = self.sql(expression, "order") 2891 null_handling = expression.args.get("null_handling") 2892 null_handling = f" {null_handling}" if null_handling else "" 2893 return_type = self.sql(expression, "return_type") 2894 return_type = f" RETURNING {return_type}" if return_type else "" 2895 strict = " STRICT" if expression.args.get("strict") else "" 2896 return self.func( 2897 "JSON_ARRAYAGG", 2898 this, 2899 suffix=f"{order}{null_handling}{return_type}{strict})", 2900 ) 2901 2902 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2903 path = self.sql(expression, "path") 2904 path = f" PATH {path}" if path else "" 2905 nested_schema = self.sql(expression, "nested_schema") 2906 2907 if nested_schema: 2908 return f"NESTED{path} {nested_schema}" 2909 2910 this = self.sql(expression, "this") 2911 kind = self.sql(expression, "kind") 2912 kind = f" {kind}" if kind else "" 2913 return f"{this}{kind}{path}" 2914 2915 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 2916 return self.func("COLUMNS", *expression.expressions) 2917 2918 def jsontable_sql(self, expression: exp.JSONTable) -> str: 2919 this = self.sql(expression, "this") 2920 path = self.sql(expression, "path") 2921 path = f", {path}" if path else "" 2922 error_handling = expression.args.get("error_handling") 2923 error_handling = f" {error_handling}" if error_handling else "" 2924 empty_handling = expression.args.get("empty_handling") 2925 empty_handling = f" {empty_handling}" if empty_handling else "" 2926 schema = self.sql(expression, "schema") 2927 return self.func( 2928 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 2929 ) 2930 2931 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 2932 this = self.sql(expression, "this") 2933 kind = self.sql(expression, "kind") 2934 path = self.sql(expression, "path") 2935 path = f" {path}" if path else "" 2936 as_json = " AS JSON" if expression.args.get("as_json") else "" 2937 return f"{this} {kind}{path}{as_json}" 2938 2939 def openjson_sql(self, expression: exp.OpenJSON) -> str: 2940 this = self.sql(expression, "this") 2941 path = self.sql(expression, "path") 2942 path = f", {path}" if path else "" 2943 expressions = self.expressions(expression) 2944 with_ = ( 2945 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 2946 if expressions 2947 else "" 2948 ) 2949 return f"OPENJSON({this}{path}){with_}" 2950 2951 def in_sql(self, expression: exp.In) -> str: 2952 query = expression.args.get("query") 2953 unnest = expression.args.get("unnest") 2954 field = expression.args.get("field") 2955 is_global = " GLOBAL" if expression.args.get("is_global") else "" 2956 2957 if query: 2958 in_sql = self.sql(query) 2959 elif unnest: 2960 in_sql = self.in_unnest_op(unnest) 2961 elif field: 2962 in_sql = self.sql(field) 2963 else: 2964 in_sql = f"({self.expressions(expression, flat=True)})" 2965 2966 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 2967 2968 def in_unnest_op(self, unnest: exp.Unnest) -> str: 2969 return f"(SELECT {self.sql(unnest)})" 2970 2971 def interval_sql(self, expression: exp.Interval) -> str: 2972 unit = self.sql(expression, "unit") 2973 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 2974 unit = self.TIME_PART_SINGULARS.get(unit, unit) 2975 unit = f" {unit}" if unit else "" 2976 2977 if self.SINGLE_STRING_INTERVAL: 2978 this = expression.this.name if expression.this else "" 2979 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 2980 2981 this = self.sql(expression, "this") 2982 if this: 2983 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 2984 this = f" {this}" if unwrapped else f" ({this})" 2985 2986 return f"INTERVAL{this}{unit}" 2987 2988 def return_sql(self, expression: exp.Return) -> str: 2989 return f"RETURN {self.sql(expression, 'this')}" 2990 2991 def reference_sql(self, expression: exp.Reference) -> str: 2992 this = self.sql(expression, "this") 2993 expressions = self.expressions(expression, flat=True) 2994 expressions = f"({expressions})" if expressions else "" 2995 options = self.expressions(expression, key="options", flat=True, sep=" ") 2996 options = f" {options}" if options else "" 2997 return f"REFERENCES {this}{expressions}{options}" 2998 2999 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3000 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3001 parent = expression.parent 3002 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3003 return self.func( 3004 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3005 ) 3006 3007 def paren_sql(self, expression: exp.Paren) -> str: 3008 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3009 return f"({sql}{self.seg(')', sep='')}" 3010 3011 def neg_sql(self, expression: exp.Neg) -> str: 3012 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3013 this_sql = self.sql(expression, "this") 3014 sep = " " if this_sql[0] == "-" else "" 3015 return f"-{sep}{this_sql}" 3016 3017 def not_sql(self, expression: exp.Not) -> str: 3018 return f"NOT {self.sql(expression, 'this')}" 3019 3020 def alias_sql(self, expression: exp.Alias) -> str: 3021 alias = self.sql(expression, "alias") 3022 alias = f" AS {alias}" if alias else "" 3023 return f"{self.sql(expression, 'this')}{alias}" 3024 3025 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3026 alias = expression.args["alias"] 3027 3028 identifier_alias = isinstance(alias, exp.Identifier) 3029 literal_alias = isinstance(alias, exp.Literal) 3030 3031 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3032 alias.replace(exp.Literal.string(alias.output_name)) 3033 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3034 alias.replace(exp.to_identifier(alias.output_name)) 3035 3036 return self.alias_sql(expression) 3037 3038 def aliases_sql(self, expression: exp.Aliases) -> str: 3039 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3040 3041 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3042 this = self.sql(expression, "this") 3043 index = self.sql(expression, "expression") 3044 return f"{this} AT {index}" 3045 3046 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3047 this = self.sql(expression, "this") 3048 zone = self.sql(expression, "zone") 3049 return f"{this} AT TIME ZONE {zone}" 3050 3051 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3052 this = self.sql(expression, "this") 3053 zone = self.sql(expression, "zone") 3054 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3055 3056 def add_sql(self, expression: exp.Add) -> str: 3057 return self.binary(expression, "+") 3058 3059 def and_sql( 3060 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3061 ) -> str: 3062 return self.connector_sql(expression, "AND", stack) 3063 3064 def or_sql( 3065 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3066 ) -> str: 3067 return self.connector_sql(expression, "OR", stack) 3068 3069 def xor_sql( 3070 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3071 ) -> str: 3072 return self.connector_sql(expression, "XOR", stack) 3073 3074 def connector_sql( 3075 self, 3076 expression: exp.Connector, 3077 op: str, 3078 stack: t.Optional[t.List[str | exp.Expression]] = None, 3079 ) -> str: 3080 if stack is not None: 3081 if expression.expressions: 3082 stack.append(self.expressions(expression, sep=f" {op} ")) 3083 else: 3084 stack.append(expression.right) 3085 if expression.comments and self.comments: 3086 for comment in expression.comments: 3087 if comment: 3088 op += f" /*{self.pad_comment(comment)}*/" 3089 stack.extend((op, expression.left)) 3090 return op 3091 3092 stack = [expression] 3093 sqls: t.List[str] = [] 3094 ops = set() 3095 3096 while stack: 3097 node = stack.pop() 3098 if isinstance(node, exp.Connector): 3099 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3100 else: 3101 sql = self.sql(node) 3102 if sqls and sqls[-1] in ops: 3103 sqls[-1] += f" {sql}" 3104 else: 3105 sqls.append(sql) 3106 3107 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3108 return sep.join(sqls) 3109 3110 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3111 return self.binary(expression, "&") 3112 3113 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3114 return self.binary(expression, "<<") 3115 3116 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3117 return f"~{self.sql(expression, 'this')}" 3118 3119 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3120 return self.binary(expression, "|") 3121 3122 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3123 return self.binary(expression, ">>") 3124 3125 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3126 return self.binary(expression, "^") 3127 3128 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3129 format_sql = self.sql(expression, "format") 3130 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3131 to_sql = self.sql(expression, "to") 3132 to_sql = f" {to_sql}" if to_sql else "" 3133 action = self.sql(expression, "action") 3134 action = f" {action}" if action else "" 3135 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})" 3136 3137 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3138 zone = self.sql(expression, "this") 3139 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3140 3141 def collate_sql(self, expression: exp.Collate) -> str: 3142 if self.COLLATE_IS_FUNC: 3143 return self.function_fallback_sql(expression) 3144 return self.binary(expression, "COLLATE") 3145 3146 def command_sql(self, expression: exp.Command) -> str: 3147 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3148 3149 def comment_sql(self, expression: exp.Comment) -> str: 3150 this = self.sql(expression, "this") 3151 kind = expression.args["kind"] 3152 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3153 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3154 expression_sql = self.sql(expression, "expression") 3155 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3156 3157 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3158 this = self.sql(expression, "this") 3159 delete = " DELETE" if expression.args.get("delete") else "" 3160 recompress = self.sql(expression, "recompress") 3161 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3162 to_disk = self.sql(expression, "to_disk") 3163 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3164 to_volume = self.sql(expression, "to_volume") 3165 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3166 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3167 3168 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3169 where = self.sql(expression, "where") 3170 group = self.sql(expression, "group") 3171 aggregates = self.expressions(expression, key="aggregates") 3172 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3173 3174 if not (where or group or aggregates) and len(expression.expressions) == 1: 3175 return f"TTL {self.expressions(expression, flat=True)}" 3176 3177 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3178 3179 def transaction_sql(self, expression: exp.Transaction) -> str: 3180 return "BEGIN" 3181 3182 def commit_sql(self, expression: exp.Commit) -> str: 3183 chain = expression.args.get("chain") 3184 if chain is not None: 3185 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3186 3187 return f"COMMIT{chain or ''}" 3188 3189 def rollback_sql(self, expression: exp.Rollback) -> str: 3190 savepoint = expression.args.get("savepoint") 3191 savepoint = f" TO {savepoint}" if savepoint else "" 3192 return f"ROLLBACK{savepoint}" 3193 3194 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3195 this = self.sql(expression, "this") 3196 3197 dtype = self.sql(expression, "dtype") 3198 if dtype: 3199 collate = self.sql(expression, "collate") 3200 collate = f" COLLATE {collate}" if collate else "" 3201 using = self.sql(expression, "using") 3202 using = f" USING {using}" if using else "" 3203 return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}" 3204 3205 default = self.sql(expression, "default") 3206 if default: 3207 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3208 3209 comment = self.sql(expression, "comment") 3210 if comment: 3211 return f"ALTER COLUMN {this} COMMENT {comment}" 3212 3213 allow_null = expression.args.get("allow_null") 3214 drop = expression.args.get("drop") 3215 3216 if not drop and not allow_null: 3217 self.unsupported("Unsupported ALTER COLUMN syntax") 3218 3219 if allow_null is not None: 3220 keyword = "DROP" if drop else "SET" 3221 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3222 3223 return f"ALTER COLUMN {this} DROP DEFAULT" 3224 3225 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3226 this = self.sql(expression, "this") 3227 if not isinstance(expression.this, exp.Var): 3228 this = f"KEY DISTKEY {this}" 3229 return f"ALTER DISTSTYLE {this}" 3230 3231 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3232 compound = " COMPOUND" if expression.args.get("compound") else "" 3233 this = self.sql(expression, "this") 3234 expressions = self.expressions(expression, flat=True) 3235 expressions = f"({expressions})" if expressions else "" 3236 return f"ALTER{compound} SORTKEY {this or expressions}" 3237 3238 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3239 if not self.RENAME_TABLE_WITH_DB: 3240 # Remove db from tables 3241 expression = expression.transform( 3242 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3243 ).assert_is(exp.AlterRename) 3244 this = self.sql(expression, "this") 3245 return f"RENAME TO {this}" 3246 3247 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3248 exists = " IF EXISTS" if expression.args.get("exists") else "" 3249 old_column = self.sql(expression, "this") 3250 new_column = self.sql(expression, "to") 3251 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3252 3253 def alterset_sql(self, expression: exp.AlterSet) -> str: 3254 exprs = self.expressions(expression, flat=True) 3255 return f"SET {exprs}" 3256 3257 def alter_sql(self, expression: exp.Alter) -> str: 3258 actions = expression.args["actions"] 3259 3260 if isinstance(actions[0], exp.ColumnDef): 3261 actions = self.add_column_sql(expression) 3262 elif isinstance(actions[0], exp.Schema): 3263 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3264 elif isinstance(actions[0], exp.Delete): 3265 actions = self.expressions(expression, key="actions", flat=True) 3266 elif isinstance(actions[0], exp.Query): 3267 actions = "AS " + self.expressions(expression, key="actions") 3268 else: 3269 actions = self.expressions(expression, key="actions", flat=True) 3270 3271 exists = " IF EXISTS" if expression.args.get("exists") else "" 3272 on_cluster = self.sql(expression, "cluster") 3273 on_cluster = f" {on_cluster}" if on_cluster else "" 3274 only = " ONLY" if expression.args.get("only") else "" 3275 options = self.expressions(expression, key="options") 3276 options = f", {options}" if options else "" 3277 kind = self.sql(expression, "kind") 3278 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3279 3280 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3281 3282 def add_column_sql(self, expression: exp.Alter) -> str: 3283 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3284 return self.expressions( 3285 expression, 3286 key="actions", 3287 prefix="ADD COLUMN ", 3288 skip_first=True, 3289 ) 3290 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3291 3292 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3293 expressions = self.expressions(expression) 3294 exists = " IF EXISTS " if expression.args.get("exists") else " " 3295 return f"DROP{exists}{expressions}" 3296 3297 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3298 return f"ADD {self.expressions(expression)}" 3299 3300 def distinct_sql(self, expression: exp.Distinct) -> str: 3301 this = self.expressions(expression, flat=True) 3302 3303 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3304 case = exp.case() 3305 for arg in expression.expressions: 3306 case = case.when(arg.is_(exp.null()), exp.null()) 3307 this = self.sql(case.else_(f"({this})")) 3308 3309 this = f" {this}" if this else "" 3310 3311 on = self.sql(expression, "on") 3312 on = f" ON {on}" if on else "" 3313 return f"DISTINCT{this}{on}" 3314 3315 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3316 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3317 3318 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3319 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3320 3321 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3322 this_sql = self.sql(expression, "this") 3323 expression_sql = self.sql(expression, "expression") 3324 kind = "MAX" if expression.args.get("max") else "MIN" 3325 return f"{this_sql} HAVING {kind} {expression_sql}" 3326 3327 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3328 return self.sql( 3329 exp.Cast( 3330 this=exp.Div(this=expression.this, expression=expression.expression), 3331 to=exp.DataType(this=exp.DataType.Type.INT), 3332 ) 3333 ) 3334 3335 def dpipe_sql(self, expression: exp.DPipe) -> str: 3336 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3337 return self.func( 3338 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3339 ) 3340 return self.binary(expression, "||") 3341 3342 def div_sql(self, expression: exp.Div) -> str: 3343 l, r = expression.left, expression.right 3344 3345 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3346 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3347 3348 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3349 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3350 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3351 3352 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3353 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3354 return self.sql( 3355 exp.cast( 3356 l / r, 3357 to=exp.DataType.Type.BIGINT, 3358 ) 3359 ) 3360 3361 return self.binary(expression, "/") 3362 3363 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3364 return self.binary(expression, "OVERLAPS") 3365 3366 def distance_sql(self, expression: exp.Distance) -> str: 3367 return self.binary(expression, "<->") 3368 3369 def dot_sql(self, expression: exp.Dot) -> str: 3370 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3371 3372 def eq_sql(self, expression: exp.EQ) -> str: 3373 return self.binary(expression, "=") 3374 3375 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3376 return self.binary(expression, ":=") 3377 3378 def escape_sql(self, expression: exp.Escape) -> str: 3379 return self.binary(expression, "ESCAPE") 3380 3381 def glob_sql(self, expression: exp.Glob) -> str: 3382 return self.binary(expression, "GLOB") 3383 3384 def gt_sql(self, expression: exp.GT) -> str: 3385 return self.binary(expression, ">") 3386 3387 def gte_sql(self, expression: exp.GTE) -> str: 3388 return self.binary(expression, ">=") 3389 3390 def ilike_sql(self, expression: exp.ILike) -> str: 3391 return self.binary(expression, "ILIKE") 3392 3393 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3394 return self.binary(expression, "ILIKE ANY") 3395 3396 def is_sql(self, expression: exp.Is) -> str: 3397 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3398 return self.sql( 3399 expression.this if expression.expression.this else exp.not_(expression.this) 3400 ) 3401 return self.binary(expression, "IS") 3402 3403 def like_sql(self, expression: exp.Like) -> str: 3404 return self.binary(expression, "LIKE") 3405 3406 def likeany_sql(self, expression: exp.LikeAny) -> str: 3407 return self.binary(expression, "LIKE ANY") 3408 3409 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3410 return self.binary(expression, "SIMILAR TO") 3411 3412 def lt_sql(self, expression: exp.LT) -> str: 3413 return self.binary(expression, "<") 3414 3415 def lte_sql(self, expression: exp.LTE) -> str: 3416 return self.binary(expression, "<=") 3417 3418 def mod_sql(self, expression: exp.Mod) -> str: 3419 return self.binary(expression, "%") 3420 3421 def mul_sql(self, expression: exp.Mul) -> str: 3422 return self.binary(expression, "*") 3423 3424 def neq_sql(self, expression: exp.NEQ) -> str: 3425 return self.binary(expression, "<>") 3426 3427 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3428 return self.binary(expression, "IS NOT DISTINCT FROM") 3429 3430 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3431 return self.binary(expression, "IS DISTINCT FROM") 3432 3433 def slice_sql(self, expression: exp.Slice) -> str: 3434 return self.binary(expression, ":") 3435 3436 def sub_sql(self, expression: exp.Sub) -> str: 3437 return self.binary(expression, "-") 3438 3439 def trycast_sql(self, expression: exp.TryCast) -> str: 3440 return self.cast_sql(expression, safe_prefix="TRY_") 3441 3442 def try_sql(self, expression: exp.Try) -> str: 3443 if not self.TRY_SUPPORTED: 3444 self.unsupported("Unsupported TRY function") 3445 return self.sql(expression, "this") 3446 3447 return self.func("TRY", expression.this) 3448 3449 def log_sql(self, expression: exp.Log) -> str: 3450 this = expression.this 3451 expr = expression.expression 3452 3453 if self.dialect.LOG_BASE_FIRST is False: 3454 this, expr = expr, this 3455 elif self.dialect.LOG_BASE_FIRST is None and expr: 3456 if this.name in ("2", "10"): 3457 return self.func(f"LOG{this.name}", expr) 3458 3459 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3460 3461 return self.func("LOG", this, expr) 3462 3463 def use_sql(self, expression: exp.Use) -> str: 3464 kind = self.sql(expression, "kind") 3465 kind = f" {kind}" if kind else "" 3466 this = self.sql(expression, "this") 3467 this = f" {this}" if this else "" 3468 return f"USE{kind}{this}" 3469 3470 def binary(self, expression: exp.Binary, op: str) -> str: 3471 sqls: t.List[str] = [] 3472 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3473 binary_type = type(expression) 3474 3475 while stack: 3476 node = stack.pop() 3477 3478 if type(node) is binary_type: 3479 op_func = node.args.get("operator") 3480 if op_func: 3481 op = f"OPERATOR({self.sql(op_func)})" 3482 3483 stack.append(node.right) 3484 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3485 stack.append(node.left) 3486 else: 3487 sqls.append(self.sql(node)) 3488 3489 return "".join(sqls) 3490 3491 def function_fallback_sql(self, expression: exp.Func) -> str: 3492 args = [] 3493 3494 for key in expression.arg_types: 3495 arg_value = expression.args.get(key) 3496 3497 if isinstance(arg_value, list): 3498 for value in arg_value: 3499 args.append(value) 3500 elif arg_value is not None: 3501 args.append(arg_value) 3502 3503 if self.normalize_functions: 3504 name = expression.sql_name() 3505 else: 3506 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3507 3508 return self.func(name, *args) 3509 3510 def func( 3511 self, 3512 name: str, 3513 *args: t.Optional[exp.Expression | str], 3514 prefix: str = "(", 3515 suffix: str = ")", 3516 normalize: bool = True, 3517 ) -> str: 3518 name = self.normalize_func(name) if normalize else name 3519 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3520 3521 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3522 arg_sqls = tuple( 3523 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3524 ) 3525 if self.pretty and self.too_wide(arg_sqls): 3526 return self.indent( 3527 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3528 ) 3529 return sep.join(arg_sqls) 3530 3531 def too_wide(self, args: t.Iterable) -> bool: 3532 return sum(len(arg) for arg in args) > self.max_text_width 3533 3534 def format_time( 3535 self, 3536 expression: exp.Expression, 3537 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3538 inverse_time_trie: t.Optional[t.Dict] = None, 3539 ) -> t.Optional[str]: 3540 return format_time( 3541 self.sql(expression, "format"), 3542 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3543 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3544 ) 3545 3546 def expressions( 3547 self, 3548 expression: t.Optional[exp.Expression] = None, 3549 key: t.Optional[str] = None, 3550 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3551 flat: bool = False, 3552 indent: bool = True, 3553 skip_first: bool = False, 3554 skip_last: bool = False, 3555 sep: str = ", ", 3556 prefix: str = "", 3557 dynamic: bool = False, 3558 new_line: bool = False, 3559 ) -> str: 3560 expressions = expression.args.get(key or "expressions") if expression else sqls 3561 3562 if not expressions: 3563 return "" 3564 3565 if flat: 3566 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3567 3568 num_sqls = len(expressions) 3569 result_sqls = [] 3570 3571 for i, e in enumerate(expressions): 3572 sql = self.sql(e, comment=False) 3573 if not sql: 3574 continue 3575 3576 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3577 3578 if self.pretty: 3579 if self.leading_comma: 3580 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3581 else: 3582 result_sqls.append( 3583 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3584 ) 3585 else: 3586 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3587 3588 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3589 if new_line: 3590 result_sqls.insert(0, "") 3591 result_sqls.append("") 3592 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3593 else: 3594 result_sql = "".join(result_sqls) 3595 3596 return ( 3597 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3598 if indent 3599 else result_sql 3600 ) 3601 3602 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3603 flat = flat or isinstance(expression.parent, exp.Properties) 3604 expressions_sql = self.expressions(expression, flat=flat) 3605 if flat: 3606 return f"{op} {expressions_sql}" 3607 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3608 3609 def naked_property(self, expression: exp.Property) -> str: 3610 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3611 if not property_name: 3612 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3613 return f"{property_name} {self.sql(expression, 'this')}" 3614 3615 def tag_sql(self, expression: exp.Tag) -> str: 3616 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3617 3618 def token_sql(self, token_type: TokenType) -> str: 3619 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3620 3621 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3622 this = self.sql(expression, "this") 3623 expressions = self.no_identify(self.expressions, expression) 3624 expressions = ( 3625 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3626 ) 3627 return f"{this}{expressions}" if expressions.strip() != "" else this 3628 3629 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3630 this = self.sql(expression, "this") 3631 expressions = self.expressions(expression, flat=True) 3632 return f"{this}({expressions})" 3633 3634 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3635 return self.binary(expression, "=>") 3636 3637 def when_sql(self, expression: exp.When) -> str: 3638 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3639 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3640 condition = self.sql(expression, "condition") 3641 condition = f" AND {condition}" if condition else "" 3642 3643 then_expression = expression.args.get("then") 3644 if isinstance(then_expression, exp.Insert): 3645 this = self.sql(then_expression, "this") 3646 this = f"INSERT {this}" if this else "INSERT" 3647 then = self.sql(then_expression, "expression") 3648 then = f"{this} VALUES {then}" if then else this 3649 elif isinstance(then_expression, exp.Update): 3650 if isinstance(then_expression.args.get("expressions"), exp.Star): 3651 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3652 else: 3653 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3654 else: 3655 then = self.sql(then_expression) 3656 return f"WHEN {matched}{source}{condition} THEN {then}" 3657 3658 def merge_sql(self, expression: exp.Merge) -> str: 3659 table = expression.this 3660 table_alias = "" 3661 3662 hints = table.args.get("hints") 3663 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3664 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3665 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3666 3667 this = self.sql(table) 3668 using = f"USING {self.sql(expression, 'using')}" 3669 on = f"ON {self.sql(expression, 'on')}" 3670 expressions = self.expressions(expression, sep=" ", indent=False) 3671 returning = self.sql(expression, "returning") 3672 if returning: 3673 expressions = f"{expressions}{returning}" 3674 3675 sep = self.sep() 3676 3677 return self.prepend_ctes( 3678 expression, 3679 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}", 3680 ) 3681 3682 @unsupported_args("format") 3683 def tochar_sql(self, expression: exp.ToChar) -> str: 3684 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3685 3686 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3687 if not self.SUPPORTS_TO_NUMBER: 3688 self.unsupported("Unsupported TO_NUMBER function") 3689 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3690 3691 fmt = expression.args.get("format") 3692 if not fmt: 3693 self.unsupported("Conversion format is required for TO_NUMBER") 3694 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3695 3696 return self.func("TO_NUMBER", expression.this, fmt) 3697 3698 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3699 this = self.sql(expression, "this") 3700 kind = self.sql(expression, "kind") 3701 settings_sql = self.expressions(expression, key="settings", sep=" ") 3702 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3703 return f"{this}({kind}{args})" 3704 3705 def dictrange_sql(self, expression: exp.DictRange) -> str: 3706 this = self.sql(expression, "this") 3707 max = self.sql(expression, "max") 3708 min = self.sql(expression, "min") 3709 return f"{this}(MIN {min} MAX {max})" 3710 3711 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3712 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3713 3714 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3715 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3716 3717 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3718 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3719 expressions = self.expressions(expression, flat=True) 3720 expressions = f" {self.wrap(expressions)}" if expressions else "" 3721 buckets = self.sql(expression, "buckets") 3722 kind = self.sql(expression, "kind") 3723 buckets = f" BUCKETS {buckets}" if buckets else "" 3724 order = self.sql(expression, "order") 3725 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3726 3727 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3728 return "" 3729 3730 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3731 expressions = self.expressions(expression, key="expressions", flat=True) 3732 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3733 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3734 buckets = self.sql(expression, "buckets") 3735 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3736 3737 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3738 this = self.sql(expression, "this") 3739 having = self.sql(expression, "having") 3740 3741 if having: 3742 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3743 3744 return self.func("ANY_VALUE", this) 3745 3746 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3747 transform = self.func("TRANSFORM", *expression.expressions) 3748 row_format_before = self.sql(expression, "row_format_before") 3749 row_format_before = f" {row_format_before}" if row_format_before else "" 3750 record_writer = self.sql(expression, "record_writer") 3751 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3752 using = f" USING {self.sql(expression, 'command_script')}" 3753 schema = self.sql(expression, "schema") 3754 schema = f" AS {schema}" if schema else "" 3755 row_format_after = self.sql(expression, "row_format_after") 3756 row_format_after = f" {row_format_after}" if row_format_after else "" 3757 record_reader = self.sql(expression, "record_reader") 3758 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3759 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3760 3761 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3762 key_block_size = self.sql(expression, "key_block_size") 3763 if key_block_size: 3764 return f"KEY_BLOCK_SIZE = {key_block_size}" 3765 3766 using = self.sql(expression, "using") 3767 if using: 3768 return f"USING {using}" 3769 3770 parser = self.sql(expression, "parser") 3771 if parser: 3772 return f"WITH PARSER {parser}" 3773 3774 comment = self.sql(expression, "comment") 3775 if comment: 3776 return f"COMMENT {comment}" 3777 3778 visible = expression.args.get("visible") 3779 if visible is not None: 3780 return "VISIBLE" if visible else "INVISIBLE" 3781 3782 engine_attr = self.sql(expression, "engine_attr") 3783 if engine_attr: 3784 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3785 3786 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3787 if secondary_engine_attr: 3788 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3789 3790 self.unsupported("Unsupported index constraint option.") 3791 return "" 3792 3793 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3794 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3795 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3796 3797 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3798 kind = self.sql(expression, "kind") 3799 kind = f"{kind} INDEX" if kind else "INDEX" 3800 this = self.sql(expression, "this") 3801 this = f" {this}" if this else "" 3802 index_type = self.sql(expression, "index_type") 3803 index_type = f" USING {index_type}" if index_type else "" 3804 expressions = self.expressions(expression, flat=True) 3805 expressions = f" ({expressions})" if expressions else "" 3806 options = self.expressions(expression, key="options", sep=" ") 3807 options = f" {options}" if options else "" 3808 return f"{kind}{this}{index_type}{expressions}{options}" 3809 3810 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3811 if self.NVL2_SUPPORTED: 3812 return self.function_fallback_sql(expression) 3813 3814 case = exp.Case().when( 3815 expression.this.is_(exp.null()).not_(copy=False), 3816 expression.args["true"], 3817 copy=False, 3818 ) 3819 else_cond = expression.args.get("false") 3820 if else_cond: 3821 case.else_(else_cond, copy=False) 3822 3823 return self.sql(case) 3824 3825 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3826 this = self.sql(expression, "this") 3827 expr = self.sql(expression, "expression") 3828 iterator = self.sql(expression, "iterator") 3829 condition = self.sql(expression, "condition") 3830 condition = f" IF {condition}" if condition else "" 3831 return f"{this} FOR {expr} IN {iterator}{condition}" 3832 3833 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3834 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3835 3836 def opclass_sql(self, expression: exp.Opclass) -> str: 3837 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3838 3839 def predict_sql(self, expression: exp.Predict) -> str: 3840 model = self.sql(expression, "this") 3841 model = f"MODEL {model}" 3842 table = self.sql(expression, "expression") 3843 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3844 parameters = self.sql(expression, "params_struct") 3845 return self.func("PREDICT", model, table, parameters or None) 3846 3847 def forin_sql(self, expression: exp.ForIn) -> str: 3848 this = self.sql(expression, "this") 3849 expression_sql = self.sql(expression, "expression") 3850 return f"FOR {this} DO {expression_sql}" 3851 3852 def refresh_sql(self, expression: exp.Refresh) -> str: 3853 this = self.sql(expression, "this") 3854 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3855 return f"REFRESH {table}{this}" 3856 3857 def toarray_sql(self, expression: exp.ToArray) -> str: 3858 arg = expression.this 3859 if not arg.type: 3860 from sqlglot.optimizer.annotate_types import annotate_types 3861 3862 arg = annotate_types(arg) 3863 3864 if arg.is_type(exp.DataType.Type.ARRAY): 3865 return self.sql(arg) 3866 3867 cond_for_null = arg.is_(exp.null()) 3868 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 3869 3870 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 3871 this = expression.this 3872 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 3873 return self.sql(this) 3874 3875 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 3876 3877 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 3878 this = expression.this 3879 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 3880 return self.sql(this) 3881 3882 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP)) 3883 3884 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 3885 this = expression.this 3886 time_format = self.format_time(expression) 3887 3888 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 3889 return self.sql( 3890 exp.cast( 3891 exp.StrToTime(this=this, format=expression.args["format"]), 3892 exp.DataType.Type.DATE, 3893 ) 3894 ) 3895 3896 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 3897 return self.sql(this) 3898 3899 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 3900 3901 def unixdate_sql(self, expression: exp.UnixDate) -> str: 3902 return self.sql( 3903 exp.func( 3904 "DATEDIFF", 3905 expression.this, 3906 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 3907 "day", 3908 ) 3909 ) 3910 3911 def lastday_sql(self, expression: exp.LastDay) -> str: 3912 if self.LAST_DAY_SUPPORTS_DATE_PART: 3913 return self.function_fallback_sql(expression) 3914 3915 unit = expression.text("unit") 3916 if unit and unit != "MONTH": 3917 self.unsupported("Date parts are not supported in LAST_DAY.") 3918 3919 return self.func("LAST_DAY", expression.this) 3920 3921 def dateadd_sql(self, expression: exp.DateAdd) -> str: 3922 from sqlglot.dialects.dialect import unit_to_str 3923 3924 return self.func( 3925 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 3926 ) 3927 3928 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 3929 if self.CAN_IMPLEMENT_ARRAY_ANY: 3930 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 3931 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 3932 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 3933 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 3934 3935 from sqlglot.dialects import Dialect 3936 3937 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 3938 if self.dialect.__class__ != Dialect: 3939 self.unsupported("ARRAY_ANY is unsupported") 3940 3941 return self.function_fallback_sql(expression) 3942 3943 def struct_sql(self, expression: exp.Struct) -> str: 3944 expression.set( 3945 "expressions", 3946 [ 3947 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 3948 if isinstance(e, exp.PropertyEQ) 3949 else e 3950 for e in expression.expressions 3951 ], 3952 ) 3953 3954 return self.function_fallback_sql(expression) 3955 3956 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 3957 low = self.sql(expression, "this") 3958 high = self.sql(expression, "expression") 3959 3960 return f"{low} TO {high}" 3961 3962 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 3963 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 3964 tables = f" {self.expressions(expression)}" 3965 3966 exists = " IF EXISTS" if expression.args.get("exists") else "" 3967 3968 on_cluster = self.sql(expression, "cluster") 3969 on_cluster = f" {on_cluster}" if on_cluster else "" 3970 3971 identity = self.sql(expression, "identity") 3972 identity = f" {identity} IDENTITY" if identity else "" 3973 3974 option = self.sql(expression, "option") 3975 option = f" {option}" if option else "" 3976 3977 partition = self.sql(expression, "partition") 3978 partition = f" {partition}" if partition else "" 3979 3980 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 3981 3982 # This transpiles T-SQL's CONVERT function 3983 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 3984 def convert_sql(self, expression: exp.Convert) -> str: 3985 to = expression.this 3986 value = expression.expression 3987 style = expression.args.get("style") 3988 safe = expression.args.get("safe") 3989 strict = expression.args.get("strict") 3990 3991 if not to or not value: 3992 return "" 3993 3994 # Retrieve length of datatype and override to default if not specified 3995 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 3996 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 3997 3998 transformed: t.Optional[exp.Expression] = None 3999 cast = exp.Cast if strict else exp.TryCast 4000 4001 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4002 if isinstance(style, exp.Literal) and style.is_int: 4003 from sqlglot.dialects.tsql import TSQL 4004 4005 style_value = style.name 4006 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4007 if not converted_style: 4008 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4009 4010 fmt = exp.Literal.string(converted_style) 4011 4012 if to.this == exp.DataType.Type.DATE: 4013 transformed = exp.StrToDate(this=value, format=fmt) 4014 elif to.this == exp.DataType.Type.DATETIME: 4015 transformed = exp.StrToTime(this=value, format=fmt) 4016 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4017 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4018 elif to.this == exp.DataType.Type.TEXT: 4019 transformed = exp.TimeToStr(this=value, format=fmt) 4020 4021 if not transformed: 4022 transformed = cast(this=value, to=to, safe=safe) 4023 4024 return self.sql(transformed) 4025 4026 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4027 this = expression.this 4028 if isinstance(this, exp.JSONPathWildcard): 4029 this = self.json_path_part(this) 4030 return f".{this}" if this else "" 4031 4032 if exp.SAFE_IDENTIFIER_RE.match(this): 4033 return f".{this}" 4034 4035 this = self.json_path_part(this) 4036 return f"[{this}]" if self.JSON_PATH_BRACKETED_KEY_SUPPORTED else f".{this}" 4037 4038 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4039 this = self.json_path_part(expression.this) 4040 return f"[{this}]" if this else "" 4041 4042 def _simplify_unless_literal(self, expression: E) -> E: 4043 if not isinstance(expression, exp.Literal): 4044 from sqlglot.optimizer.simplify import simplify 4045 4046 expression = simplify(expression, dialect=self.dialect) 4047 4048 return expression 4049 4050 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4051 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4052 # The first modifier here will be the one closest to the AggFunc's arg 4053 mods = sorted( 4054 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4055 key=lambda x: 0 4056 if isinstance(x, exp.HavingMax) 4057 else (1 if isinstance(x, exp.Order) else 2), 4058 ) 4059 4060 if mods: 4061 mod = mods[0] 4062 this = expression.__class__(this=mod.this.copy()) 4063 this.meta["inline"] = True 4064 mod.this.replace(this) 4065 return self.sql(expression.this) 4066 4067 agg_func = expression.find(exp.AggFunc) 4068 4069 if agg_func: 4070 return self.sql(agg_func)[:-1] + f" {text})" 4071 4072 return f"{self.sql(expression, 'this')} {text}" 4073 4074 def _replace_line_breaks(self, string: str) -> str: 4075 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4076 if self.pretty: 4077 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4078 return string 4079 4080 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4081 option = self.sql(expression, "this") 4082 4083 if expression.expressions: 4084 upper = option.upper() 4085 4086 # Snowflake FILE_FORMAT options are separated by whitespace 4087 sep = " " if upper == "FILE_FORMAT" else ", " 4088 4089 # Databricks copy/format options do not set their list of values with EQ 4090 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4091 values = self.expressions(expression, flat=True, sep=sep) 4092 return f"{option}{op}({values})" 4093 4094 value = self.sql(expression, "expression") 4095 4096 if not value: 4097 return option 4098 4099 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4100 4101 return f"{option}{op}{value}" 4102 4103 def credentials_sql(self, expression: exp.Credentials) -> str: 4104 cred_expr = expression.args.get("credentials") 4105 if isinstance(cred_expr, exp.Literal): 4106 # Redshift case: CREDENTIALS <string> 4107 credentials = self.sql(expression, "credentials") 4108 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4109 else: 4110 # Snowflake case: CREDENTIALS = (...) 4111 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4112 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4113 4114 storage = self.sql(expression, "storage") 4115 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4116 4117 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4118 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4119 4120 iam_role = self.sql(expression, "iam_role") 4121 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4122 4123 region = self.sql(expression, "region") 4124 region = f" REGION {region}" if region else "" 4125 4126 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4127 4128 def copy_sql(self, expression: exp.Copy) -> str: 4129 this = self.sql(expression, "this") 4130 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4131 4132 credentials = self.sql(expression, "credentials") 4133 credentials = self.seg(credentials) if credentials else "" 4134 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4135 files = self.expressions(expression, key="files", flat=True) 4136 4137 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4138 params = self.expressions( 4139 expression, 4140 key="params", 4141 sep=sep, 4142 new_line=True, 4143 skip_last=True, 4144 skip_first=True, 4145 indent=self.COPY_PARAMS_ARE_WRAPPED, 4146 ) 4147 4148 if params: 4149 if self.COPY_PARAMS_ARE_WRAPPED: 4150 params = f" WITH ({params})" 4151 elif not self.pretty: 4152 params = f" {params}" 4153 4154 return f"COPY{this}{kind} {files}{credentials}{params}" 4155 4156 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4157 return "" 4158 4159 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4160 on_sql = "ON" if expression.args.get("on") else "OFF" 4161 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4162 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4163 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4164 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4165 4166 if filter_col or retention_period: 4167 on_sql = self.func("ON", filter_col, retention_period) 4168 4169 return f"DATA_DELETION={on_sql}" 4170 4171 def maskingpolicycolumnconstraint_sql( 4172 self, expression: exp.MaskingPolicyColumnConstraint 4173 ) -> str: 4174 this = self.sql(expression, "this") 4175 expressions = self.expressions(expression, flat=True) 4176 expressions = f" USING ({expressions})" if expressions else "" 4177 return f"MASKING POLICY {this}{expressions}" 4178 4179 def gapfill_sql(self, expression: exp.GapFill) -> str: 4180 this = self.sql(expression, "this") 4181 this = f"TABLE {this}" 4182 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4183 4184 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4185 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4186 4187 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4188 this = self.sql(expression, "this") 4189 expr = expression.expression 4190 4191 if isinstance(expr, exp.Func): 4192 # T-SQL's CLR functions are case sensitive 4193 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4194 else: 4195 expr = self.sql(expression, "expression") 4196 4197 return self.scope_resolution(expr, this) 4198 4199 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4200 if self.PARSE_JSON_NAME is None: 4201 return self.sql(expression.this) 4202 4203 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4204 4205 def rand_sql(self, expression: exp.Rand) -> str: 4206 lower = self.sql(expression, "lower") 4207 upper = self.sql(expression, "upper") 4208 4209 if lower and upper: 4210 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4211 return self.func("RAND", expression.this) 4212 4213 def changes_sql(self, expression: exp.Changes) -> str: 4214 information = self.sql(expression, "information") 4215 information = f"INFORMATION => {information}" 4216 at_before = self.sql(expression, "at_before") 4217 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4218 end = self.sql(expression, "end") 4219 end = f"{self.seg('')}{end}" if end else "" 4220 4221 return f"CHANGES ({information}){at_before}{end}" 4222 4223 def pad_sql(self, expression: exp.Pad) -> str: 4224 prefix = "L" if expression.args.get("is_left") else "R" 4225 4226 fill_pattern = self.sql(expression, "fill_pattern") or None 4227 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4228 fill_pattern = "' '" 4229 4230 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4231 4232 def summarize_sql(self, expression: exp.Summarize) -> str: 4233 table = " TABLE" if expression.args.get("table") else "" 4234 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4235 4236 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4237 generate_series = exp.GenerateSeries(**expression.args) 4238 4239 parent = expression.parent 4240 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4241 parent = parent.parent 4242 4243 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4244 return self.sql(exp.Unnest(expressions=[generate_series])) 4245 4246 if isinstance(parent, exp.Select): 4247 self.unsupported("GenerateSeries projection unnesting is not supported.") 4248 4249 return self.sql(generate_series) 4250 4251 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4252 exprs = expression.expressions 4253 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4254 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4255 else: 4256 rhs = self.expressions(expression) 4257 4258 return self.func(name, expression.this, rhs or None) 4259 4260 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4261 if self.SUPPORTS_CONVERT_TIMEZONE: 4262 return self.function_fallback_sql(expression) 4263 4264 source_tz = expression.args.get("source_tz") 4265 target_tz = expression.args.get("target_tz") 4266 timestamp = expression.args.get("timestamp") 4267 4268 if source_tz and timestamp: 4269 timestamp = exp.AtTimeZone( 4270 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4271 ) 4272 4273 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4274 4275 return self.sql(expr) 4276 4277 def json_sql(self, expression: exp.JSON) -> str: 4278 this = self.sql(expression, "this") 4279 this = f" {this}" if this else "" 4280 4281 _with = expression.args.get("with") 4282 4283 if _with is None: 4284 with_sql = "" 4285 elif not _with: 4286 with_sql = " WITHOUT" 4287 else: 4288 with_sql = " WITH" 4289 4290 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4291 4292 return f"JSON{this}{with_sql}{unique_sql}" 4293 4294 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4295 def _generate_on_options(arg: t.Any) -> str: 4296 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4297 4298 path = self.sql(expression, "path") 4299 returning = self.sql(expression, "returning") 4300 returning = f" RETURNING {returning}" if returning else "" 4301 4302 on_condition = self.sql(expression, "on_condition") 4303 on_condition = f" {on_condition}" if on_condition else "" 4304 4305 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4306 4307 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4308 else_ = "ELSE " if expression.args.get("else_") else "" 4309 condition = self.sql(expression, "expression") 4310 condition = f"WHEN {condition} THEN " if condition else else_ 4311 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4312 return f"{condition}{insert}" 4313 4314 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4315 kind = self.sql(expression, "kind") 4316 expressions = self.seg(self.expressions(expression, sep=" ")) 4317 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4318 return res 4319 4320 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4321 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4322 empty = expression.args.get("empty") 4323 empty = ( 4324 f"DEFAULT {empty} ON EMPTY" 4325 if isinstance(empty, exp.Expression) 4326 else self.sql(expression, "empty") 4327 ) 4328 4329 error = expression.args.get("error") 4330 error = ( 4331 f"DEFAULT {error} ON ERROR" 4332 if isinstance(error, exp.Expression) 4333 else self.sql(expression, "error") 4334 ) 4335 4336 if error and empty: 4337 error = ( 4338 f"{empty} {error}" 4339 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4340 else f"{error} {empty}" 4341 ) 4342 empty = "" 4343 4344 null = self.sql(expression, "null") 4345 4346 return f"{empty}{error}{null}" 4347 4348 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4349 this = self.sql(expression, "this") 4350 path = self.sql(expression, "path") 4351 4352 passing = self.expressions(expression, "passing") 4353 passing = f" PASSING {passing}" if passing else "" 4354 4355 on_condition = self.sql(expression, "on_condition") 4356 on_condition = f" {on_condition}" if on_condition else "" 4357 4358 path = f"{path}{passing}{on_condition}" 4359 4360 return self.func("JSON_EXISTS", this, path) 4361 4362 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4363 array_agg = self.function_fallback_sql(expression) 4364 4365 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4366 parent = expression.parent 4367 if isinstance(parent, exp.Filter): 4368 parent_cond = parent.expression.this 4369 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4370 else: 4371 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4372 this = expression.this 4373 this_sql = ( 4374 self.expressions(this) 4375 if isinstance(this, exp.Distinct) 4376 else self.sql(expression, "this") 4377 ) 4378 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4379 4380 return array_agg 4381 4382 def apply_sql(self, expression: exp.Apply) -> str: 4383 this = self.sql(expression, "this") 4384 expr = self.sql(expression, "expression") 4385 4386 return f"{this} APPLY({expr})" 4387 4388 def grant_sql(self, expression: exp.Grant) -> str: 4389 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4390 4391 kind = self.sql(expression, "kind") 4392 kind = f" {kind}" if kind else "" 4393 4394 securable = self.sql(expression, "securable") 4395 securable = f" {securable}" if securable else "" 4396 4397 principals = self.expressions(expression, key="principals", flat=True) 4398 4399 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4400 4401 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4402 4403 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4404 this = self.sql(expression, "this") 4405 columns = self.expressions(expression, flat=True) 4406 columns = f"({columns})" if columns else "" 4407 4408 return f"{this}{columns}" 4409 4410 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4411 this = self.sql(expression, "this") 4412 4413 kind = self.sql(expression, "kind") 4414 kind = f"{kind} " if kind else "" 4415 4416 return f"{kind}{this}" 4417 4418 def columns_sql(self, expression: exp.Columns): 4419 func = self.function_fallback_sql(expression) 4420 if expression.args.get("unpack"): 4421 func = f"*{func}" 4422 4423 return func 4424 4425 def overlay_sql(self, expression: exp.Overlay): 4426 this = self.sql(expression, "this") 4427 expr = self.sql(expression, "expression") 4428 from_sql = self.sql(expression, "from") 4429 for_sql = self.sql(expression, "for") 4430 for_sql = f" FOR {for_sql}" if for_sql else "" 4431 4432 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4433 4434 @unsupported_args("format") 4435 def todouble_sql(self, expression: exp.ToDouble) -> str: 4436 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4437 4438 def string_sql(self, expression: exp.String) -> str: 4439 this = expression.this 4440 zone = expression.args.get("zone") 4441 4442 if zone: 4443 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4444 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4445 # set for source_tz to transpile the time conversion before the STRING cast 4446 this = exp.ConvertTimezone( 4447 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4448 ) 4449 4450 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
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.ArrayContainsAll: lambda self, e: self.binary(e, "@>"), 119 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 120 exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}", 121 exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}", 122 exp.CaseSpecificColumnConstraint: lambda _, 123 e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC", 124 exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}", 125 exp.CharacterSetProperty: lambda self, 126 e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}", 127 exp.ClusteredColumnConstraint: lambda self, 128 e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})", 129 exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}", 130 exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}", 131 exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}", 132 exp.CopyGrantsProperty: lambda *_: "COPY GRANTS", 133 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 134 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 135 exp.DynamicProperty: lambda *_: "DYNAMIC", 136 exp.EmptyProperty: lambda *_: "EMPTY", 137 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 138 exp.EphemeralColumnConstraint: lambda self, 139 e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}", 140 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 141 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 142 exp.Except: lambda self, e: self.set_operations(e), 143 exp.ExternalProperty: lambda *_: "EXTERNAL", 144 exp.GlobalProperty: lambda *_: "GLOBAL", 145 exp.HeapProperty: lambda *_: "HEAP", 146 exp.IcebergProperty: lambda *_: "ICEBERG", 147 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 148 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 149 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 150 exp.Intersect: lambda self, e: self.set_operations(e), 151 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 152 exp.LanguageProperty: lambda self, e: self.naked_property(e), 153 exp.LocationProperty: lambda self, e: self.naked_property(e), 154 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 155 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 156 exp.NonClusteredColumnConstraint: lambda self, 157 e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})", 158 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 159 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 160 exp.OnCommitProperty: lambda _, 161 e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS", 162 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 163 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 164 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 165 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 166 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 167 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 168 exp.ProjectionPolicyColumnConstraint: lambda self, 169 e: f"PROJECTION POLICY {self.sql(e, 'this')}", 170 exp.RemoteWithConnectionModelProperty: lambda self, 171 e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}", 172 exp.ReturnsProperty: lambda self, e: ( 173 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 174 ), 175 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 176 exp.SecureProperty: lambda *_: "SECURE", 177 exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}", 178 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 179 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 180 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 181 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 182 exp.SqlReadWriteProperty: lambda _, e: e.name, 183 exp.SqlSecurityProperty: lambda _, 184 e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}", 185 exp.StabilityProperty: lambda _, e: e.name, 186 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 187 exp.StreamingTableProperty: lambda *_: "STREAMING", 188 exp.StrictProperty: lambda *_: "STRICT", 189 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 190 exp.TemporaryProperty: lambda *_: "TEMPORARY", 191 exp.TagColumnConstraint: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 192 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 193 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 194 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 195 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 196 exp.TransientProperty: lambda *_: "TRANSIENT", 197 exp.Union: lambda self, e: self.set_operations(e), 198 exp.UnloggedProperty: lambda *_: "UNLOGGED", 199 exp.Uuid: lambda *_: "UUID()", 200 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 201 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 202 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 203 exp.VolatileProperty: lambda *_: "VOLATILE", 204 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 205 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 206 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 207 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 208 } 209 210 # Whether null ordering is supported in order by 211 # True: Full Support, None: No support, False: No support for certain cases 212 # such as window specifications, aggregate functions etc 213 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 214 215 # Whether ignore nulls is inside the agg or outside. 216 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 217 IGNORE_NULLS_IN_FUNC = False 218 219 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 220 LOCKING_READS_SUPPORTED = False 221 222 # Whether the EXCEPT and INTERSECT operations can return duplicates 223 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 224 225 # Wrap derived values in parens, usually standard but spark doesn't support it 226 WRAP_DERIVED_VALUES = True 227 228 # Whether create function uses an AS before the RETURN 229 CREATE_FUNCTION_RETURN_AS = True 230 231 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 232 MATCHED_BY_SOURCE = True 233 234 # Whether the INTERVAL expression works only with values like '1 day' 235 SINGLE_STRING_INTERVAL = False 236 237 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 238 INTERVAL_ALLOWS_PLURAL_FORM = True 239 240 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 241 LIMIT_FETCH = "ALL" 242 243 # Whether limit and fetch allows expresions or just limits 244 LIMIT_ONLY_LITERALS = False 245 246 # Whether a table is allowed to be renamed with a db 247 RENAME_TABLE_WITH_DB = True 248 249 # The separator for grouping sets and rollups 250 GROUPINGS_SEP = "," 251 252 # The string used for creating an index on a table 253 INDEX_ON = "ON" 254 255 # Whether join hints should be generated 256 JOIN_HINTS = True 257 258 # Whether table hints should be generated 259 TABLE_HINTS = True 260 261 # Whether query hints should be generated 262 QUERY_HINTS = True 263 264 # What kind of separator to use for query hints 265 QUERY_HINT_SEP = ", " 266 267 # Whether comparing against booleans (e.g. x IS TRUE) is supported 268 IS_BOOL_ALLOWED = True 269 270 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 271 DUPLICATE_KEY_UPDATE_WITH_SET = True 272 273 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 274 LIMIT_IS_TOP = False 275 276 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 277 RETURNING_END = True 278 279 # Whether to generate an unquoted value for EXTRACT's date part argument 280 EXTRACT_ALLOWS_QUOTES = True 281 282 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 283 TZ_TO_WITH_TIME_ZONE = False 284 285 # Whether the NVL2 function is supported 286 NVL2_SUPPORTED = True 287 288 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 289 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 290 291 # Whether VALUES statements can be used as derived tables. 292 # MySQL 5 and Redshift do not allow this, so when False, it will convert 293 # SELECT * VALUES into SELECT UNION 294 VALUES_AS_TABLE = True 295 296 # Whether the word COLUMN is included when adding a column with ALTER TABLE 297 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 298 299 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 300 UNNEST_WITH_ORDINALITY = True 301 302 # Whether FILTER (WHERE cond) can be used for conditional aggregation 303 AGGREGATE_FILTER_SUPPORTED = True 304 305 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 306 SEMI_ANTI_JOIN_WITH_SIDE = True 307 308 # Whether to include the type of a computed column in the CREATE DDL 309 COMPUTED_COLUMN_WITH_TYPE = True 310 311 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 312 SUPPORTS_TABLE_COPY = True 313 314 # Whether parentheses are required around the table sample's expression 315 TABLESAMPLE_REQUIRES_PARENS = True 316 317 # Whether a table sample clause's size needs to be followed by the ROWS keyword 318 TABLESAMPLE_SIZE_IS_ROWS = True 319 320 # The keyword(s) to use when generating a sample clause 321 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 322 323 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 324 TABLESAMPLE_WITH_METHOD = True 325 326 # The keyword to use when specifying the seed of a sample clause 327 TABLESAMPLE_SEED_KEYWORD = "SEED" 328 329 # Whether COLLATE is a function instead of a binary operator 330 COLLATE_IS_FUNC = False 331 332 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 333 DATA_TYPE_SPECIFIERS_ALLOWED = False 334 335 # Whether conditions require booleans WHERE x = 0 vs WHERE x 336 ENSURE_BOOLS = False 337 338 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 339 CTE_RECURSIVE_KEYWORD_REQUIRED = True 340 341 # Whether CONCAT requires >1 arguments 342 SUPPORTS_SINGLE_ARG_CONCAT = True 343 344 # Whether LAST_DAY function supports a date part argument 345 LAST_DAY_SUPPORTS_DATE_PART = True 346 347 # Whether named columns are allowed in table aliases 348 SUPPORTS_TABLE_ALIAS_COLUMNS = True 349 350 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 351 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 352 353 # What delimiter to use for separating JSON key/value pairs 354 JSON_KEY_VALUE_PAIR_SEP = ":" 355 356 # INSERT OVERWRITE TABLE x override 357 INSERT_OVERWRITE = " OVERWRITE TABLE" 358 359 # Whether the SELECT .. INTO syntax is used instead of CTAS 360 SUPPORTS_SELECT_INTO = False 361 362 # Whether UNLOGGED tables can be created 363 SUPPORTS_UNLOGGED_TABLES = False 364 365 # Whether the CREATE TABLE LIKE statement is supported 366 SUPPORTS_CREATE_TABLE_LIKE = True 367 368 # Whether the LikeProperty needs to be specified inside of the schema clause 369 LIKE_PROPERTY_INSIDE_SCHEMA = False 370 371 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 372 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 373 MULTI_ARG_DISTINCT = True 374 375 # Whether the JSON extraction operators expect a value of type JSON 376 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 377 378 # Whether bracketed keys like ["foo"] are supported in JSON paths 379 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 380 381 # Whether to escape keys using single quotes in JSON paths 382 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 383 384 # The JSONPathPart expressions supported by this dialect 385 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 386 387 # Whether any(f(x) for x in array) can be implemented by this dialect 388 CAN_IMPLEMENT_ARRAY_ANY = False 389 390 # Whether the function TO_NUMBER is supported 391 SUPPORTS_TO_NUMBER = True 392 393 # Whether or not set op modifiers apply to the outer set op or select. 394 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 395 # True means limit 1 happens after the set op, False means it it happens on y. 396 SET_OP_MODIFIERS = True 397 398 # Whether parameters from COPY statement are wrapped in parentheses 399 COPY_PARAMS_ARE_WRAPPED = True 400 401 # Whether values of params are set with "=" token or empty space 402 COPY_PARAMS_EQ_REQUIRED = False 403 404 # Whether COPY statement has INTO keyword 405 COPY_HAS_INTO_KEYWORD = True 406 407 # Whether the conditional TRY(expression) function is supported 408 TRY_SUPPORTED = True 409 410 # Whether the UESCAPE syntax in unicode strings is supported 411 SUPPORTS_UESCAPE = True 412 413 # The keyword to use when generating a star projection with excluded columns 414 STAR_EXCEPT = "EXCEPT" 415 416 # The HEX function name 417 HEX_FUNC = "HEX" 418 419 # The keywords to use when prefixing & separating WITH based properties 420 WITH_PROPERTIES_PREFIX = "WITH" 421 422 # Whether to quote the generated expression of exp.JsonPath 423 QUOTE_JSON_PATH = True 424 425 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 426 PAD_FILL_PATTERN_IS_REQUIRED = False 427 428 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 429 SUPPORTS_EXPLODING_PROJECTIONS = True 430 431 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 432 ARRAY_CONCAT_IS_VAR_LEN = True 433 434 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 435 SUPPORTS_CONVERT_TIMEZONE = False 436 437 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 438 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 439 440 TYPE_MAPPING = { 441 exp.DataType.Type.NCHAR: "CHAR", 442 exp.DataType.Type.NVARCHAR: "VARCHAR", 443 exp.DataType.Type.MEDIUMTEXT: "TEXT", 444 exp.DataType.Type.LONGTEXT: "TEXT", 445 exp.DataType.Type.TINYTEXT: "TEXT", 446 exp.DataType.Type.MEDIUMBLOB: "BLOB", 447 exp.DataType.Type.LONGBLOB: "BLOB", 448 exp.DataType.Type.TINYBLOB: "BLOB", 449 exp.DataType.Type.INET: "INET", 450 exp.DataType.Type.ROWVERSION: "VARBINARY", 451 } 452 453 TIME_PART_SINGULARS = { 454 "MICROSECONDS": "MICROSECOND", 455 "SECONDS": "SECOND", 456 "MINUTES": "MINUTE", 457 "HOURS": "HOUR", 458 "DAYS": "DAY", 459 "WEEKS": "WEEK", 460 "MONTHS": "MONTH", 461 "QUARTERS": "QUARTER", 462 "YEARS": "YEAR", 463 } 464 465 AFTER_HAVING_MODIFIER_TRANSFORMS = { 466 "cluster": lambda self, e: self.sql(e, "cluster"), 467 "distribute": lambda self, e: self.sql(e, "distribute"), 468 "sort": lambda self, e: self.sql(e, "sort"), 469 "windows": lambda self, e: ( 470 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 471 if e.args.get("windows") 472 else "" 473 ), 474 "qualify": lambda self, e: self.sql(e, "qualify"), 475 } 476 477 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 478 479 STRUCT_DELIMITER = ("<", ">") 480 481 PARAMETER_TOKEN = "@" 482 NAMED_PLACEHOLDER_TOKEN = ":" 483 484 PROPERTIES_LOCATION = { 485 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 486 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 487 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 488 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 489 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 490 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 491 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 492 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 493 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 494 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 495 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 496 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 497 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 498 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 499 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 500 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 501 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 502 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 503 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 504 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 505 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 506 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 507 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 508 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 509 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 510 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 511 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 512 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 513 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 514 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 515 exp.HeapProperty: exp.Properties.Location.POST_WITH, 516 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 517 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 518 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 519 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 520 exp.JournalProperty: exp.Properties.Location.POST_NAME, 521 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 522 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 523 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 524 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 525 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 526 exp.LogProperty: exp.Properties.Location.POST_NAME, 527 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 528 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 529 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 530 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 531 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 532 exp.Order: exp.Properties.Location.POST_SCHEMA, 533 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 534 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 535 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 536 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 537 exp.Property: exp.Properties.Location.POST_WITH, 538 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 539 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 540 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 541 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 542 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 543 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 544 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 545 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 546 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 547 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 548 exp.Set: exp.Properties.Location.POST_SCHEMA, 549 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 550 exp.SetProperty: exp.Properties.Location.POST_CREATE, 551 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 552 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 553 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 554 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 555 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 556 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 557 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 558 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 559 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 560 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 561 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 562 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 563 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 564 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 565 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 566 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 567 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 568 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 569 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 570 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 571 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 572 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 573 } 574 575 # Keywords that can't be used as unquoted identifier names 576 RESERVED_KEYWORDS: t.Set[str] = set() 577 578 # Expressions whose comments are separated from them for better formatting 579 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 580 exp.Command, 581 exp.Create, 582 exp.Delete, 583 exp.Drop, 584 exp.From, 585 exp.Insert, 586 exp.Join, 587 exp.MultitableInserts, 588 exp.Select, 589 exp.SetOperation, 590 exp.Update, 591 exp.Where, 592 exp.With, 593 ) 594 595 # Expressions that should not have their comments generated in maybe_comment 596 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 597 exp.Binary, 598 exp.SetOperation, 599 ) 600 601 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 602 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 603 exp.Column, 604 exp.Literal, 605 exp.Neg, 606 exp.Paren, 607 ) 608 609 PARAMETERIZABLE_TEXT_TYPES = { 610 exp.DataType.Type.NVARCHAR, 611 exp.DataType.Type.VARCHAR, 612 exp.DataType.Type.CHAR, 613 exp.DataType.Type.NCHAR, 614 } 615 616 # Expressions that need to have all CTEs under them bubbled up to them 617 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 618 619 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 620 621 __slots__ = ( 622 "pretty", 623 "identify", 624 "normalize", 625 "pad", 626 "_indent", 627 "normalize_functions", 628 "unsupported_level", 629 "max_unsupported", 630 "leading_comma", 631 "max_text_width", 632 "comments", 633 "dialect", 634 "unsupported_messages", 635 "_escaped_quote_end", 636 "_escaped_identifier_end", 637 "_next_name", 638 "_identifier_start", 639 "_identifier_end", 640 ) 641 642 def __init__( 643 self, 644 pretty: t.Optional[bool] = None, 645 identify: str | bool = False, 646 normalize: bool = False, 647 pad: int = 2, 648 indent: int = 2, 649 normalize_functions: t.Optional[str | bool] = None, 650 unsupported_level: ErrorLevel = ErrorLevel.WARN, 651 max_unsupported: int = 3, 652 leading_comma: bool = False, 653 max_text_width: int = 80, 654 comments: bool = True, 655 dialect: DialectType = None, 656 ): 657 import sqlglot 658 from sqlglot.dialects import Dialect 659 660 self.pretty = pretty if pretty is not None else sqlglot.pretty 661 self.identify = identify 662 self.normalize = normalize 663 self.pad = pad 664 self._indent = indent 665 self.unsupported_level = unsupported_level 666 self.max_unsupported = max_unsupported 667 self.leading_comma = leading_comma 668 self.max_text_width = max_text_width 669 self.comments = comments 670 self.dialect = Dialect.get_or_raise(dialect) 671 672 # This is both a Dialect property and a Generator argument, so we prioritize the latter 673 self.normalize_functions = ( 674 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 675 ) 676 677 self.unsupported_messages: t.List[str] = [] 678 self._escaped_quote_end: str = ( 679 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 680 ) 681 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 682 683 self._next_name = name_sequence("_t") 684 685 self._identifier_start = self.dialect.IDENTIFIER_START 686 self._identifier_end = self.dialect.IDENTIFIER_END 687 688 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 689 """ 690 Generates the SQL string corresponding to the given syntax tree. 691 692 Args: 693 expression: The syntax tree. 694 copy: Whether to copy the expression. The generator performs mutations so 695 it is safer to copy. 696 697 Returns: 698 The SQL string corresponding to `expression`. 699 """ 700 if copy: 701 expression = expression.copy() 702 703 expression = self.preprocess(expression) 704 705 self.unsupported_messages = [] 706 sql = self.sql(expression).strip() 707 708 if self.pretty: 709 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 710 711 if self.unsupported_level == ErrorLevel.IGNORE: 712 return sql 713 714 if self.unsupported_level == ErrorLevel.WARN: 715 for msg in self.unsupported_messages: 716 logger.warning(msg) 717 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 718 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 719 720 return sql 721 722 def preprocess(self, expression: exp.Expression) -> exp.Expression: 723 """Apply generic preprocessing transformations to a given expression.""" 724 expression = self._move_ctes_to_top_level(expression) 725 726 if self.ENSURE_BOOLS: 727 from sqlglot.transforms import ensure_bools 728 729 expression = ensure_bools(expression) 730 731 return expression 732 733 def _move_ctes_to_top_level(self, expression: E) -> E: 734 if ( 735 not expression.parent 736 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 737 and any(node.parent is not expression for node in expression.find_all(exp.With)) 738 ): 739 from sqlglot.transforms import move_ctes_to_top_level 740 741 expression = move_ctes_to_top_level(expression) 742 return expression 743 744 def unsupported(self, message: str) -> None: 745 if self.unsupported_level == ErrorLevel.IMMEDIATE: 746 raise UnsupportedError(message) 747 self.unsupported_messages.append(message) 748 749 def sep(self, sep: str = " ") -> str: 750 return f"{sep.strip()}\n" if self.pretty else sep 751 752 def seg(self, sql: str, sep: str = " ") -> str: 753 return f"{self.sep(sep)}{sql}" 754 755 def pad_comment(self, comment: str) -> str: 756 comment = " " + comment if comment[0].strip() else comment 757 comment = comment + " " if comment[-1].strip() else comment 758 return comment 759 760 def maybe_comment( 761 self, 762 sql: str, 763 expression: t.Optional[exp.Expression] = None, 764 comments: t.Optional[t.List[str]] = None, 765 separated: bool = False, 766 ) -> str: 767 comments = ( 768 ((expression and expression.comments) if comments is None else comments) # type: ignore 769 if self.comments 770 else None 771 ) 772 773 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 774 return sql 775 776 comments_sql = " ".join( 777 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 778 ) 779 780 if not comments_sql: 781 return sql 782 783 comments_sql = self._replace_line_breaks(comments_sql) 784 785 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 786 return ( 787 f"{self.sep()}{comments_sql}{sql}" 788 if not sql or sql[0].isspace() 789 else f"{comments_sql}{self.sep()}{sql}" 790 ) 791 792 return f"{sql} {comments_sql}" 793 794 def wrap(self, expression: exp.Expression | str) -> str: 795 this_sql = ( 796 self.sql(expression) 797 if isinstance(expression, exp.UNWRAPPED_QUERIES) 798 else self.sql(expression, "this") 799 ) 800 if not this_sql: 801 return "()" 802 803 this_sql = self.indent(this_sql, level=1, pad=0) 804 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 805 806 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 807 original = self.identify 808 self.identify = False 809 result = func(*args, **kwargs) 810 self.identify = original 811 return result 812 813 def normalize_func(self, name: str) -> str: 814 if self.normalize_functions == "upper" or self.normalize_functions is True: 815 return name.upper() 816 if self.normalize_functions == "lower": 817 return name.lower() 818 return name 819 820 def indent( 821 self, 822 sql: str, 823 level: int = 0, 824 pad: t.Optional[int] = None, 825 skip_first: bool = False, 826 skip_last: bool = False, 827 ) -> str: 828 if not self.pretty or not sql: 829 return sql 830 831 pad = self.pad if pad is None else pad 832 lines = sql.split("\n") 833 834 return "\n".join( 835 ( 836 line 837 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 838 else f"{' ' * (level * self._indent + pad)}{line}" 839 ) 840 for i, line in enumerate(lines) 841 ) 842 843 def sql( 844 self, 845 expression: t.Optional[str | exp.Expression], 846 key: t.Optional[str] = None, 847 comment: bool = True, 848 ) -> str: 849 if not expression: 850 return "" 851 852 if isinstance(expression, str): 853 return expression 854 855 if key: 856 value = expression.args.get(key) 857 if value: 858 return self.sql(value) 859 return "" 860 861 transform = self.TRANSFORMS.get(expression.__class__) 862 863 if callable(transform): 864 sql = transform(self, expression) 865 elif isinstance(expression, exp.Expression): 866 exp_handler_name = f"{expression.key}_sql" 867 868 if hasattr(self, exp_handler_name): 869 sql = getattr(self, exp_handler_name)(expression) 870 elif isinstance(expression, exp.Func): 871 sql = self.function_fallback_sql(expression) 872 elif isinstance(expression, exp.Property): 873 sql = self.property_sql(expression) 874 else: 875 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 876 else: 877 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 878 879 return self.maybe_comment(sql, expression) if self.comments and comment else sql 880 881 def uncache_sql(self, expression: exp.Uncache) -> str: 882 table = self.sql(expression, "this") 883 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 884 return f"UNCACHE TABLE{exists_sql} {table}" 885 886 def cache_sql(self, expression: exp.Cache) -> str: 887 lazy = " LAZY" if expression.args.get("lazy") else "" 888 table = self.sql(expression, "this") 889 options = expression.args.get("options") 890 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 891 sql = self.sql(expression, "expression") 892 sql = f" AS{self.sep()}{sql}" if sql else "" 893 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 894 return self.prepend_ctes(expression, sql) 895 896 def characterset_sql(self, expression: exp.CharacterSet) -> str: 897 if isinstance(expression.parent, exp.Cast): 898 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 899 default = "DEFAULT " if expression.args.get("default") else "" 900 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 901 902 def column_parts(self, expression: exp.Column) -> str: 903 return ".".join( 904 self.sql(part) 905 for part in ( 906 expression.args.get("catalog"), 907 expression.args.get("db"), 908 expression.args.get("table"), 909 expression.args.get("this"), 910 ) 911 if part 912 ) 913 914 def column_sql(self, expression: exp.Column) -> str: 915 join_mark = " (+)" if expression.args.get("join_mark") else "" 916 917 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 918 join_mark = "" 919 self.unsupported("Outer join syntax using the (+) operator is not supported.") 920 921 return f"{self.column_parts(expression)}{join_mark}" 922 923 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 924 this = self.sql(expression, "this") 925 this = f" {this}" if this else "" 926 position = self.sql(expression, "position") 927 return f"{position}{this}" 928 929 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 930 column = self.sql(expression, "this") 931 kind = self.sql(expression, "kind") 932 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 933 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 934 kind = f"{sep}{kind}" if kind else "" 935 constraints = f" {constraints}" if constraints else "" 936 position = self.sql(expression, "position") 937 position = f" {position}" if position else "" 938 939 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 940 kind = "" 941 942 return f"{exists}{column}{kind}{constraints}{position}" 943 944 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 945 this = self.sql(expression, "this") 946 kind_sql = self.sql(expression, "kind").strip() 947 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 948 949 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 950 this = self.sql(expression, "this") 951 if expression.args.get("not_null"): 952 persisted = " PERSISTED NOT NULL" 953 elif expression.args.get("persisted"): 954 persisted = " PERSISTED" 955 else: 956 persisted = "" 957 return f"AS {this}{persisted}" 958 959 def autoincrementcolumnconstraint_sql(self, _) -> str: 960 return self.token_sql(TokenType.AUTO_INCREMENT) 961 962 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 963 if isinstance(expression.this, list): 964 this = self.wrap(self.expressions(expression, key="this", flat=True)) 965 else: 966 this = self.sql(expression, "this") 967 968 return f"COMPRESS {this}" 969 970 def generatedasidentitycolumnconstraint_sql( 971 self, expression: exp.GeneratedAsIdentityColumnConstraint 972 ) -> str: 973 this = "" 974 if expression.this is not None: 975 on_null = " ON NULL" if expression.args.get("on_null") else "" 976 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 977 978 start = expression.args.get("start") 979 start = f"START WITH {start}" if start else "" 980 increment = expression.args.get("increment") 981 increment = f" INCREMENT BY {increment}" if increment else "" 982 minvalue = expression.args.get("minvalue") 983 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 984 maxvalue = expression.args.get("maxvalue") 985 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 986 cycle = expression.args.get("cycle") 987 cycle_sql = "" 988 989 if cycle is not None: 990 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 991 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 992 993 sequence_opts = "" 994 if start or increment or cycle_sql: 995 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 996 sequence_opts = f" ({sequence_opts.strip()})" 997 998 expr = self.sql(expression, "expression") 999 expr = f"({expr})" if expr else "IDENTITY" 1000 1001 return f"GENERATED{this} AS {expr}{sequence_opts}" 1002 1003 def generatedasrowcolumnconstraint_sql( 1004 self, expression: exp.GeneratedAsRowColumnConstraint 1005 ) -> str: 1006 start = "START" if expression.args.get("start") else "END" 1007 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1008 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1009 1010 def periodforsystemtimeconstraint_sql( 1011 self, expression: exp.PeriodForSystemTimeConstraint 1012 ) -> str: 1013 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1014 1015 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1016 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1017 1018 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1019 return f"AS {self.sql(expression, 'this')}" 1020 1021 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1022 desc = expression.args.get("desc") 1023 if desc is not None: 1024 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1025 return "PRIMARY KEY" 1026 1027 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1028 this = self.sql(expression, "this") 1029 this = f" {this}" if this else "" 1030 index_type = expression.args.get("index_type") 1031 index_type = f" USING {index_type}" if index_type else "" 1032 on_conflict = self.sql(expression, "on_conflict") 1033 on_conflict = f" {on_conflict}" if on_conflict else "" 1034 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1035 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1036 1037 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1038 return self.sql(expression, "this") 1039 1040 def create_sql(self, expression: exp.Create) -> str: 1041 kind = self.sql(expression, "kind") 1042 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1043 properties = expression.args.get("properties") 1044 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1045 1046 this = self.createable_sql(expression, properties_locs) 1047 1048 properties_sql = "" 1049 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1050 exp.Properties.Location.POST_WITH 1051 ): 1052 properties_sql = self.sql( 1053 exp.Properties( 1054 expressions=[ 1055 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1056 *properties_locs[exp.Properties.Location.POST_WITH], 1057 ] 1058 ) 1059 ) 1060 1061 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1062 properties_sql = self.sep() + properties_sql 1063 elif not self.pretty: 1064 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1065 properties_sql = f" {properties_sql}" 1066 1067 begin = " BEGIN" if expression.args.get("begin") else "" 1068 end = " END" if expression.args.get("end") else "" 1069 1070 expression_sql = self.sql(expression, "expression") 1071 if expression_sql: 1072 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1073 1074 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1075 postalias_props_sql = "" 1076 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1077 postalias_props_sql = self.properties( 1078 exp.Properties( 1079 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1080 ), 1081 wrapped=False, 1082 ) 1083 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1084 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1085 1086 postindex_props_sql = "" 1087 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1088 postindex_props_sql = self.properties( 1089 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1090 wrapped=False, 1091 prefix=" ", 1092 ) 1093 1094 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1095 indexes = f" {indexes}" if indexes else "" 1096 index_sql = indexes + postindex_props_sql 1097 1098 replace = " OR REPLACE" if expression.args.get("replace") else "" 1099 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1100 unique = " UNIQUE" if expression.args.get("unique") else "" 1101 1102 clustered = expression.args.get("clustered") 1103 if clustered is None: 1104 clustered_sql = "" 1105 elif clustered: 1106 clustered_sql = " CLUSTERED COLUMNSTORE" 1107 else: 1108 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1109 1110 postcreate_props_sql = "" 1111 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1112 postcreate_props_sql = self.properties( 1113 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1114 sep=" ", 1115 prefix=" ", 1116 wrapped=False, 1117 ) 1118 1119 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1120 1121 postexpression_props_sql = "" 1122 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1123 postexpression_props_sql = self.properties( 1124 exp.Properties( 1125 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1126 ), 1127 sep=" ", 1128 prefix=" ", 1129 wrapped=False, 1130 ) 1131 1132 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1133 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1134 no_schema_binding = ( 1135 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1136 ) 1137 1138 clone = self.sql(expression, "clone") 1139 clone = f" {clone}" if clone else "" 1140 1141 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1142 return self.prepend_ctes(expression, expression_sql) 1143 1144 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1145 start = self.sql(expression, "start") 1146 start = f"START WITH {start}" if start else "" 1147 increment = self.sql(expression, "increment") 1148 increment = f" INCREMENT BY {increment}" if increment else "" 1149 minvalue = self.sql(expression, "minvalue") 1150 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1151 maxvalue = self.sql(expression, "maxvalue") 1152 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1153 owned = self.sql(expression, "owned") 1154 owned = f" OWNED BY {owned}" if owned else "" 1155 1156 cache = expression.args.get("cache") 1157 if cache is None: 1158 cache_str = "" 1159 elif cache is True: 1160 cache_str = " CACHE" 1161 else: 1162 cache_str = f" CACHE {cache}" 1163 1164 options = self.expressions(expression, key="options", flat=True, sep=" ") 1165 options = f" {options}" if options else "" 1166 1167 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1168 1169 def clone_sql(self, expression: exp.Clone) -> str: 1170 this = self.sql(expression, "this") 1171 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1172 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1173 return f"{shallow}{keyword} {this}" 1174 1175 def describe_sql(self, expression: exp.Describe) -> str: 1176 style = expression.args.get("style") 1177 style = f" {style}" if style else "" 1178 partition = self.sql(expression, "partition") 1179 partition = f" {partition}" if partition else "" 1180 return f"DESCRIBE{style} {self.sql(expression, 'this')}{partition}" 1181 1182 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1183 tag = self.sql(expression, "tag") 1184 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1185 1186 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1187 with_ = self.sql(expression, "with") 1188 if with_: 1189 sql = f"{with_}{self.sep()}{sql}" 1190 return sql 1191 1192 def with_sql(self, expression: exp.With) -> str: 1193 sql = self.expressions(expression, flat=True) 1194 recursive = ( 1195 "RECURSIVE " 1196 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1197 else "" 1198 ) 1199 1200 return f"WITH {recursive}{sql}" 1201 1202 def cte_sql(self, expression: exp.CTE) -> str: 1203 alias = expression.args.get("alias") 1204 if alias: 1205 alias.add_comments(expression.pop_comments()) 1206 1207 alias_sql = self.sql(expression, "alias") 1208 1209 materialized = expression.args.get("materialized") 1210 if materialized is False: 1211 materialized = "NOT MATERIALIZED " 1212 elif materialized: 1213 materialized = "MATERIALIZED " 1214 1215 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1216 1217 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1218 alias = self.sql(expression, "this") 1219 columns = self.expressions(expression, key="columns", flat=True) 1220 columns = f"({columns})" if columns else "" 1221 1222 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1223 columns = "" 1224 self.unsupported("Named columns are not supported in table alias.") 1225 1226 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1227 alias = self._next_name() 1228 1229 return f"{alias}{columns}" 1230 1231 def bitstring_sql(self, expression: exp.BitString) -> str: 1232 this = self.sql(expression, "this") 1233 if self.dialect.BIT_START: 1234 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1235 return f"{int(this, 2)}" 1236 1237 def hexstring_sql(self, expression: exp.HexString) -> str: 1238 this = self.sql(expression, "this") 1239 if self.dialect.HEX_START: 1240 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1241 return f"{int(this, 16)}" 1242 1243 def bytestring_sql(self, expression: exp.ByteString) -> str: 1244 this = self.sql(expression, "this") 1245 if self.dialect.BYTE_START: 1246 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1247 return this 1248 1249 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1250 this = self.sql(expression, "this") 1251 escape = expression.args.get("escape") 1252 1253 if self.dialect.UNICODE_START: 1254 escape_substitute = r"\\\1" 1255 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1256 else: 1257 escape_substitute = r"\\u\1" 1258 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1259 1260 if escape: 1261 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1262 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1263 else: 1264 escape_pattern = ESCAPED_UNICODE_RE 1265 escape_sql = "" 1266 1267 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1268 this = escape_pattern.sub(escape_substitute, this) 1269 1270 return f"{left_quote}{this}{right_quote}{escape_sql}" 1271 1272 def rawstring_sql(self, expression: exp.RawString) -> str: 1273 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1274 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1275 1276 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1277 this = self.sql(expression, "this") 1278 specifier = self.sql(expression, "expression") 1279 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1280 return f"{this}{specifier}" 1281 1282 def datatype_sql(self, expression: exp.DataType) -> str: 1283 nested = "" 1284 values = "" 1285 interior = self.expressions(expression, flat=True) 1286 1287 type_value = expression.this 1288 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1289 type_sql = self.sql(expression, "kind") 1290 else: 1291 type_sql = ( 1292 self.TYPE_MAPPING.get(type_value, type_value.value) 1293 if isinstance(type_value, exp.DataType.Type) 1294 else type_value 1295 ) 1296 1297 if interior: 1298 if expression.args.get("nested"): 1299 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1300 if expression.args.get("values") is not None: 1301 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1302 values = self.expressions(expression, key="values", flat=True) 1303 values = f"{delimiters[0]}{values}{delimiters[1]}" 1304 elif type_value == exp.DataType.Type.INTERVAL: 1305 nested = f" {interior}" 1306 else: 1307 nested = f"({interior})" 1308 1309 type_sql = f"{type_sql}{nested}{values}" 1310 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1311 exp.DataType.Type.TIMETZ, 1312 exp.DataType.Type.TIMESTAMPTZ, 1313 ): 1314 type_sql = f"{type_sql} WITH TIME ZONE" 1315 1316 return type_sql 1317 1318 def directory_sql(self, expression: exp.Directory) -> str: 1319 local = "LOCAL " if expression.args.get("local") else "" 1320 row_format = self.sql(expression, "row_format") 1321 row_format = f" {row_format}" if row_format else "" 1322 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1323 1324 def delete_sql(self, expression: exp.Delete) -> str: 1325 this = self.sql(expression, "this") 1326 this = f" FROM {this}" if this else "" 1327 using = self.sql(expression, "using") 1328 using = f" USING {using}" if using else "" 1329 cluster = self.sql(expression, "cluster") 1330 cluster = f" {cluster}" if cluster else "" 1331 where = self.sql(expression, "where") 1332 returning = self.sql(expression, "returning") 1333 limit = self.sql(expression, "limit") 1334 tables = self.expressions(expression, key="tables") 1335 tables = f" {tables}" if tables else "" 1336 if self.RETURNING_END: 1337 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1338 else: 1339 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1340 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1341 1342 def drop_sql(self, expression: exp.Drop) -> str: 1343 this = self.sql(expression, "this") 1344 expressions = self.expressions(expression, flat=True) 1345 expressions = f" ({expressions})" if expressions else "" 1346 kind = expression.args["kind"] 1347 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1348 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1349 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1350 on_cluster = self.sql(expression, "cluster") 1351 on_cluster = f" {on_cluster}" if on_cluster else "" 1352 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1353 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1354 cascade = " CASCADE" if expression.args.get("cascade") else "" 1355 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1356 purge = " PURGE" if expression.args.get("purge") else "" 1357 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1358 1359 def set_operation(self, expression: exp.SetOperation) -> str: 1360 op_type = type(expression) 1361 op_name = op_type.key.upper() 1362 1363 distinct = expression.args.get("distinct") 1364 if ( 1365 distinct is False 1366 and op_type in (exp.Except, exp.Intersect) 1367 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1368 ): 1369 self.unsupported(f"{op_name} ALL is not supported") 1370 1371 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1372 1373 if distinct is None: 1374 distinct = default_distinct 1375 if distinct is None: 1376 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1377 1378 if distinct is default_distinct: 1379 kind = "" 1380 else: 1381 kind = " DISTINCT" if distinct else " ALL" 1382 1383 by_name = " BY NAME" if expression.args.get("by_name") else "" 1384 return f"{op_name}{kind}{by_name}" 1385 1386 def set_operations(self, expression: exp.SetOperation) -> str: 1387 if not self.SET_OP_MODIFIERS: 1388 limit = expression.args.get("limit") 1389 order = expression.args.get("order") 1390 1391 if limit or order: 1392 select = self._move_ctes_to_top_level( 1393 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1394 ) 1395 1396 if limit: 1397 select = select.limit(limit.pop(), copy=False) 1398 if order: 1399 select = select.order_by(order.pop(), copy=False) 1400 return self.sql(select) 1401 1402 sqls: t.List[str] = [] 1403 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1404 1405 while stack: 1406 node = stack.pop() 1407 1408 if isinstance(node, exp.SetOperation): 1409 stack.append(node.expression) 1410 stack.append( 1411 self.maybe_comment( 1412 self.set_operation(node), comments=node.comments, separated=True 1413 ) 1414 ) 1415 stack.append(node.this) 1416 else: 1417 sqls.append(self.sql(node)) 1418 1419 this = self.sep().join(sqls) 1420 this = self.query_modifiers(expression, this) 1421 return self.prepend_ctes(expression, this) 1422 1423 def fetch_sql(self, expression: exp.Fetch) -> str: 1424 direction = expression.args.get("direction") 1425 direction = f" {direction}" if direction else "" 1426 count = self.sql(expression, "count") 1427 count = f" {count}" if count else "" 1428 if expression.args.get("percent"): 1429 count = f"{count} PERCENT" 1430 with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY" 1431 return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}" 1432 1433 def filter_sql(self, expression: exp.Filter) -> str: 1434 if self.AGGREGATE_FILTER_SUPPORTED: 1435 this = self.sql(expression, "this") 1436 where = self.sql(expression, "expression").strip() 1437 return f"{this} FILTER({where})" 1438 1439 agg = expression.this 1440 agg_arg = agg.this 1441 cond = expression.expression.this 1442 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1443 return self.sql(agg) 1444 1445 def hint_sql(self, expression: exp.Hint) -> str: 1446 if not self.QUERY_HINTS: 1447 self.unsupported("Hints are not supported") 1448 return "" 1449 1450 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1451 1452 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1453 using = self.sql(expression, "using") 1454 using = f" USING {using}" if using else "" 1455 columns = self.expressions(expression, key="columns", flat=True) 1456 columns = f"({columns})" if columns else "" 1457 partition_by = self.expressions(expression, key="partition_by", flat=True) 1458 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1459 where = self.sql(expression, "where") 1460 include = self.expressions(expression, key="include", flat=True) 1461 if include: 1462 include = f" INCLUDE ({include})" 1463 with_storage = self.expressions(expression, key="with_storage", flat=True) 1464 with_storage = f" WITH ({with_storage})" if with_storage else "" 1465 tablespace = self.sql(expression, "tablespace") 1466 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1467 on = self.sql(expression, "on") 1468 on = f" ON {on}" if on else "" 1469 1470 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1471 1472 def index_sql(self, expression: exp.Index) -> str: 1473 unique = "UNIQUE " if expression.args.get("unique") else "" 1474 primary = "PRIMARY " if expression.args.get("primary") else "" 1475 amp = "AMP " if expression.args.get("amp") else "" 1476 name = self.sql(expression, "this") 1477 name = f"{name} " if name else "" 1478 table = self.sql(expression, "table") 1479 table = f"{self.INDEX_ON} {table}" if table else "" 1480 1481 index = "INDEX " if not table else "" 1482 1483 params = self.sql(expression, "params") 1484 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1485 1486 def identifier_sql(self, expression: exp.Identifier) -> str: 1487 text = expression.name 1488 lower = text.lower() 1489 text = lower if self.normalize and not expression.quoted else text 1490 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1491 if ( 1492 expression.quoted 1493 or self.dialect.can_identify(text, self.identify) 1494 or lower in self.RESERVED_KEYWORDS 1495 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1496 ): 1497 text = f"{self._identifier_start}{text}{self._identifier_end}" 1498 return text 1499 1500 def hex_sql(self, expression: exp.Hex) -> str: 1501 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1502 if self.dialect.HEX_LOWERCASE: 1503 text = self.func("LOWER", text) 1504 1505 return text 1506 1507 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1508 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1509 if not self.dialect.HEX_LOWERCASE: 1510 text = self.func("LOWER", text) 1511 return text 1512 1513 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1514 input_format = self.sql(expression, "input_format") 1515 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1516 output_format = self.sql(expression, "output_format") 1517 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1518 return self.sep().join((input_format, output_format)) 1519 1520 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1521 string = self.sql(exp.Literal.string(expression.name)) 1522 return f"{prefix}{string}" 1523 1524 def partition_sql(self, expression: exp.Partition) -> str: 1525 return f"PARTITION({self.expressions(expression, flat=True)})" 1526 1527 def properties_sql(self, expression: exp.Properties) -> str: 1528 root_properties = [] 1529 with_properties = [] 1530 1531 for p in expression.expressions: 1532 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1533 if p_loc == exp.Properties.Location.POST_WITH: 1534 with_properties.append(p) 1535 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1536 root_properties.append(p) 1537 1538 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1539 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1540 1541 if root_props and with_props and not self.pretty: 1542 with_props = " " + with_props 1543 1544 return root_props + with_props 1545 1546 def root_properties(self, properties: exp.Properties) -> str: 1547 if properties.expressions: 1548 return self.expressions(properties, indent=False, sep=" ") 1549 return "" 1550 1551 def properties( 1552 self, 1553 properties: exp.Properties, 1554 prefix: str = "", 1555 sep: str = ", ", 1556 suffix: str = "", 1557 wrapped: bool = True, 1558 ) -> str: 1559 if properties.expressions: 1560 expressions = self.expressions(properties, sep=sep, indent=False) 1561 if expressions: 1562 expressions = self.wrap(expressions) if wrapped else expressions 1563 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1564 return "" 1565 1566 def with_properties(self, properties: exp.Properties) -> str: 1567 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1568 1569 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1570 properties_locs = defaultdict(list) 1571 for p in properties.expressions: 1572 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1573 if p_loc != exp.Properties.Location.UNSUPPORTED: 1574 properties_locs[p_loc].append(p) 1575 else: 1576 self.unsupported(f"Unsupported property {p.key}") 1577 1578 return properties_locs 1579 1580 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1581 if isinstance(expression.this, exp.Dot): 1582 return self.sql(expression, "this") 1583 return f"'{expression.name}'" if string_key else expression.name 1584 1585 def property_sql(self, expression: exp.Property) -> str: 1586 property_cls = expression.__class__ 1587 if property_cls == exp.Property: 1588 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1589 1590 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1591 if not property_name: 1592 self.unsupported(f"Unsupported property {expression.key}") 1593 1594 return f"{property_name}={self.sql(expression, 'this')}" 1595 1596 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1597 if self.SUPPORTS_CREATE_TABLE_LIKE: 1598 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1599 options = f" {options}" if options else "" 1600 1601 like = f"LIKE {self.sql(expression, 'this')}{options}" 1602 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1603 like = f"({like})" 1604 1605 return like 1606 1607 if expression.expressions: 1608 self.unsupported("Transpilation of LIKE property options is unsupported") 1609 1610 select = exp.select("*").from_(expression.this).limit(0) 1611 return f"AS {self.sql(select)}" 1612 1613 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1614 no = "NO " if expression.args.get("no") else "" 1615 protection = " PROTECTION" if expression.args.get("protection") else "" 1616 return f"{no}FALLBACK{protection}" 1617 1618 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1619 no = "NO " if expression.args.get("no") else "" 1620 local = expression.args.get("local") 1621 local = f"{local} " if local else "" 1622 dual = "DUAL " if expression.args.get("dual") else "" 1623 before = "BEFORE " if expression.args.get("before") else "" 1624 after = "AFTER " if expression.args.get("after") else "" 1625 return f"{no}{local}{dual}{before}{after}JOURNAL" 1626 1627 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1628 freespace = self.sql(expression, "this") 1629 percent = " PERCENT" if expression.args.get("percent") else "" 1630 return f"FREESPACE={freespace}{percent}" 1631 1632 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1633 if expression.args.get("default"): 1634 property = "DEFAULT" 1635 elif expression.args.get("on"): 1636 property = "ON" 1637 else: 1638 property = "OFF" 1639 return f"CHECKSUM={property}" 1640 1641 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1642 if expression.args.get("no"): 1643 return "NO MERGEBLOCKRATIO" 1644 if expression.args.get("default"): 1645 return "DEFAULT MERGEBLOCKRATIO" 1646 1647 percent = " PERCENT" if expression.args.get("percent") else "" 1648 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1649 1650 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1651 default = expression.args.get("default") 1652 minimum = expression.args.get("minimum") 1653 maximum = expression.args.get("maximum") 1654 if default or minimum or maximum: 1655 if default: 1656 prop = "DEFAULT" 1657 elif minimum: 1658 prop = "MINIMUM" 1659 else: 1660 prop = "MAXIMUM" 1661 return f"{prop} DATABLOCKSIZE" 1662 units = expression.args.get("units") 1663 units = f" {units}" if units else "" 1664 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1665 1666 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1667 autotemp = expression.args.get("autotemp") 1668 always = expression.args.get("always") 1669 default = expression.args.get("default") 1670 manual = expression.args.get("manual") 1671 never = expression.args.get("never") 1672 1673 if autotemp is not None: 1674 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1675 elif always: 1676 prop = "ALWAYS" 1677 elif default: 1678 prop = "DEFAULT" 1679 elif manual: 1680 prop = "MANUAL" 1681 elif never: 1682 prop = "NEVER" 1683 return f"BLOCKCOMPRESSION={prop}" 1684 1685 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1686 no = expression.args.get("no") 1687 no = " NO" if no else "" 1688 concurrent = expression.args.get("concurrent") 1689 concurrent = " CONCURRENT" if concurrent else "" 1690 target = self.sql(expression, "target") 1691 target = f" {target}" if target else "" 1692 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1693 1694 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1695 if isinstance(expression.this, list): 1696 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1697 if expression.this: 1698 modulus = self.sql(expression, "this") 1699 remainder = self.sql(expression, "expression") 1700 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1701 1702 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1703 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1704 return f"FROM ({from_expressions}) TO ({to_expressions})" 1705 1706 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1707 this = self.sql(expression, "this") 1708 1709 for_values_or_default = expression.expression 1710 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1711 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1712 else: 1713 for_values_or_default = " DEFAULT" 1714 1715 return f"PARTITION OF {this}{for_values_or_default}" 1716 1717 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1718 kind = expression.args.get("kind") 1719 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1720 for_or_in = expression.args.get("for_or_in") 1721 for_or_in = f" {for_or_in}" if for_or_in else "" 1722 lock_type = expression.args.get("lock_type") 1723 override = " OVERRIDE" if expression.args.get("override") else "" 1724 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1725 1726 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1727 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1728 statistics = expression.args.get("statistics") 1729 statistics_sql = "" 1730 if statistics is not None: 1731 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1732 return f"{data_sql}{statistics_sql}" 1733 1734 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1735 this = self.sql(expression, "this") 1736 this = f"HISTORY_TABLE={this}" if this else "" 1737 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1738 data_consistency = ( 1739 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1740 ) 1741 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1742 retention_period = ( 1743 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1744 ) 1745 1746 if this: 1747 on_sql = self.func("ON", this, data_consistency, retention_period) 1748 else: 1749 on_sql = "ON" if expression.args.get("on") else "OFF" 1750 1751 sql = f"SYSTEM_VERSIONING={on_sql}" 1752 1753 return f"WITH({sql})" if expression.args.get("with") else sql 1754 1755 def insert_sql(self, expression: exp.Insert) -> str: 1756 hint = self.sql(expression, "hint") 1757 overwrite = expression.args.get("overwrite") 1758 1759 if isinstance(expression.this, exp.Directory): 1760 this = " OVERWRITE" if overwrite else " INTO" 1761 else: 1762 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1763 1764 stored = self.sql(expression, "stored") 1765 stored = f" {stored}" if stored else "" 1766 alternative = expression.args.get("alternative") 1767 alternative = f" OR {alternative}" if alternative else "" 1768 ignore = " IGNORE" if expression.args.get("ignore") else "" 1769 is_function = expression.args.get("is_function") 1770 if is_function: 1771 this = f"{this} FUNCTION" 1772 this = f"{this} {self.sql(expression, 'this')}" 1773 1774 exists = " IF EXISTS" if expression.args.get("exists") else "" 1775 where = self.sql(expression, "where") 1776 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1777 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1778 on_conflict = self.sql(expression, "conflict") 1779 on_conflict = f" {on_conflict}" if on_conflict else "" 1780 by_name = " BY NAME" if expression.args.get("by_name") else "" 1781 returning = self.sql(expression, "returning") 1782 1783 if self.RETURNING_END: 1784 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1785 else: 1786 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1787 1788 partition_by = self.sql(expression, "partition") 1789 partition_by = f" {partition_by}" if partition_by else "" 1790 settings = self.sql(expression, "settings") 1791 settings = f" {settings}" if settings else "" 1792 1793 source = self.sql(expression, "source") 1794 source = f"TABLE {source}" if source else "" 1795 1796 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1797 return self.prepend_ctes(expression, sql) 1798 1799 def introducer_sql(self, expression: exp.Introducer) -> str: 1800 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1801 1802 def kill_sql(self, expression: exp.Kill) -> str: 1803 kind = self.sql(expression, "kind") 1804 kind = f" {kind}" if kind else "" 1805 this = self.sql(expression, "this") 1806 this = f" {this}" if this else "" 1807 return f"KILL{kind}{this}" 1808 1809 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1810 return expression.name 1811 1812 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1813 return expression.name 1814 1815 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1816 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1817 1818 constraint = self.sql(expression, "constraint") 1819 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1820 1821 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1822 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1823 action = self.sql(expression, "action") 1824 1825 expressions = self.expressions(expression, flat=True) 1826 if expressions: 1827 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1828 expressions = f" {set_keyword}{expressions}" 1829 1830 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}" 1831 1832 def returning_sql(self, expression: exp.Returning) -> str: 1833 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1834 1835 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1836 fields = self.sql(expression, "fields") 1837 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1838 escaped = self.sql(expression, "escaped") 1839 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1840 items = self.sql(expression, "collection_items") 1841 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1842 keys = self.sql(expression, "map_keys") 1843 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1844 lines = self.sql(expression, "lines") 1845 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1846 null = self.sql(expression, "null") 1847 null = f" NULL DEFINED AS {null}" if null else "" 1848 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1849 1850 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1851 return f"WITH ({self.expressions(expression, flat=True)})" 1852 1853 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1854 this = f"{self.sql(expression, 'this')} INDEX" 1855 target = self.sql(expression, "target") 1856 target = f" FOR {target}" if target else "" 1857 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1858 1859 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1860 this = self.sql(expression, "this") 1861 kind = self.sql(expression, "kind") 1862 expr = self.sql(expression, "expression") 1863 return f"{this} ({kind} => {expr})" 1864 1865 def table_parts(self, expression: exp.Table) -> str: 1866 return ".".join( 1867 self.sql(part) 1868 for part in ( 1869 expression.args.get("catalog"), 1870 expression.args.get("db"), 1871 expression.args.get("this"), 1872 ) 1873 if part is not None 1874 ) 1875 1876 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1877 table = self.table_parts(expression) 1878 only = "ONLY " if expression.args.get("only") else "" 1879 partition = self.sql(expression, "partition") 1880 partition = f" {partition}" if partition else "" 1881 version = self.sql(expression, "version") 1882 version = f" {version}" if version else "" 1883 alias = self.sql(expression, "alias") 1884 alias = f"{sep}{alias}" if alias else "" 1885 1886 sample = self.sql(expression, "sample") 1887 if self.dialect.ALIAS_POST_TABLESAMPLE: 1888 sample_pre_alias = sample 1889 sample_post_alias = "" 1890 else: 1891 sample_pre_alias = "" 1892 sample_post_alias = sample 1893 1894 hints = self.expressions(expression, key="hints", sep=" ") 1895 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1896 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1897 joins = self.indent( 1898 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1899 ) 1900 laterals = self.expressions(expression, key="laterals", sep="") 1901 1902 file_format = self.sql(expression, "format") 1903 if file_format: 1904 pattern = self.sql(expression, "pattern") 1905 pattern = f", PATTERN => {pattern}" if pattern else "" 1906 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1907 1908 ordinality = expression.args.get("ordinality") or "" 1909 if ordinality: 1910 ordinality = f" WITH ORDINALITY{alias}" 1911 alias = "" 1912 1913 when = self.sql(expression, "when") 1914 if when: 1915 table = f"{table} {when}" 1916 1917 changes = self.sql(expression, "changes") 1918 changes = f" {changes}" if changes else "" 1919 1920 rows_from = self.expressions(expression, key="rows_from") 1921 if rows_from: 1922 table = f"ROWS FROM {self.wrap(rows_from)}" 1923 1924 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 1925 1926 def tablesample_sql( 1927 self, 1928 expression: exp.TableSample, 1929 tablesample_keyword: t.Optional[str] = None, 1930 ) -> str: 1931 method = self.sql(expression, "method") 1932 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 1933 numerator = self.sql(expression, "bucket_numerator") 1934 denominator = self.sql(expression, "bucket_denominator") 1935 field = self.sql(expression, "bucket_field") 1936 field = f" ON {field}" if field else "" 1937 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 1938 seed = self.sql(expression, "seed") 1939 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 1940 1941 size = self.sql(expression, "size") 1942 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 1943 size = f"{size} ROWS" 1944 1945 percent = self.sql(expression, "percent") 1946 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 1947 percent = f"{percent} PERCENT" 1948 1949 expr = f"{bucket}{percent}{size}" 1950 if self.TABLESAMPLE_REQUIRES_PARENS: 1951 expr = f"({expr})" 1952 1953 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 1954 1955 def pivot_sql(self, expression: exp.Pivot) -> str: 1956 expressions = self.expressions(expression, flat=True) 1957 1958 if expression.this: 1959 this = self.sql(expression, "this") 1960 if not expressions: 1961 return f"UNPIVOT {this}" 1962 1963 on = f"{self.seg('ON')} {expressions}" 1964 using = self.expressions(expression, key="using", flat=True) 1965 using = f"{self.seg('USING')} {using}" if using else "" 1966 group = self.sql(expression, "group") 1967 return f"PIVOT {this}{on}{using}{group}" 1968 1969 alias = self.sql(expression, "alias") 1970 alias = f" AS {alias}" if alias else "" 1971 direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT") 1972 1973 field = self.sql(expression, "field") 1974 1975 include_nulls = expression.args.get("include_nulls") 1976 if include_nulls is not None: 1977 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 1978 else: 1979 nulls = "" 1980 1981 default_on_null = self.sql(expression, "default_on_null") 1982 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 1983 return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 1984 1985 def version_sql(self, expression: exp.Version) -> str: 1986 this = f"FOR {expression.name}" 1987 kind = expression.text("kind") 1988 expr = self.sql(expression, "expression") 1989 return f"{this} {kind} {expr}" 1990 1991 def tuple_sql(self, expression: exp.Tuple) -> str: 1992 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 1993 1994 def update_sql(self, expression: exp.Update) -> str: 1995 this = self.sql(expression, "this") 1996 set_sql = self.expressions(expression, flat=True) 1997 from_sql = self.sql(expression, "from") 1998 where_sql = self.sql(expression, "where") 1999 returning = self.sql(expression, "returning") 2000 order = self.sql(expression, "order") 2001 limit = self.sql(expression, "limit") 2002 if self.RETURNING_END: 2003 expression_sql = f"{from_sql}{where_sql}{returning}" 2004 else: 2005 expression_sql = f"{returning}{from_sql}{where_sql}" 2006 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2007 return self.prepend_ctes(expression, sql) 2008 2009 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2010 values_as_table = values_as_table and self.VALUES_AS_TABLE 2011 2012 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2013 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2014 args = self.expressions(expression) 2015 alias = self.sql(expression, "alias") 2016 values = f"VALUES{self.seg('')}{args}" 2017 values = ( 2018 f"({values})" 2019 if self.WRAP_DERIVED_VALUES 2020 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2021 else values 2022 ) 2023 return f"{values} AS {alias}" if alias else values 2024 2025 # Converts `VALUES...` expression into a series of select unions. 2026 alias_node = expression.args.get("alias") 2027 column_names = alias_node and alias_node.columns 2028 2029 selects: t.List[exp.Query] = [] 2030 2031 for i, tup in enumerate(expression.expressions): 2032 row = tup.expressions 2033 2034 if i == 0 and column_names: 2035 row = [ 2036 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2037 ] 2038 2039 selects.append(exp.Select(expressions=row)) 2040 2041 if self.pretty: 2042 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2043 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2044 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2045 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2046 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2047 2048 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2049 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2050 return f"({unions}){alias}" 2051 2052 def var_sql(self, expression: exp.Var) -> str: 2053 return self.sql(expression, "this") 2054 2055 @unsupported_args("expressions") 2056 def into_sql(self, expression: exp.Into) -> str: 2057 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2058 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2059 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2060 2061 def from_sql(self, expression: exp.From) -> str: 2062 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2063 2064 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2065 grouping_sets = self.expressions(expression, indent=False) 2066 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2067 2068 def rollup_sql(self, expression: exp.Rollup) -> str: 2069 expressions = self.expressions(expression, indent=False) 2070 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2071 2072 def cube_sql(self, expression: exp.Cube) -> str: 2073 expressions = self.expressions(expression, indent=False) 2074 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2075 2076 def group_sql(self, expression: exp.Group) -> str: 2077 group_by_all = expression.args.get("all") 2078 if group_by_all is True: 2079 modifier = " ALL" 2080 elif group_by_all is False: 2081 modifier = " DISTINCT" 2082 else: 2083 modifier = "" 2084 2085 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2086 2087 grouping_sets = self.expressions(expression, key="grouping_sets") 2088 cube = self.expressions(expression, key="cube") 2089 rollup = self.expressions(expression, key="rollup") 2090 2091 groupings = csv( 2092 self.seg(grouping_sets) if grouping_sets else "", 2093 self.seg(cube) if cube else "", 2094 self.seg(rollup) if rollup else "", 2095 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2096 sep=self.GROUPINGS_SEP, 2097 ) 2098 2099 if ( 2100 expression.expressions 2101 and groupings 2102 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2103 ): 2104 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2105 2106 return f"{group_by}{groupings}" 2107 2108 def having_sql(self, expression: exp.Having) -> str: 2109 this = self.indent(self.sql(expression, "this")) 2110 return f"{self.seg('HAVING')}{self.sep()}{this}" 2111 2112 def connect_sql(self, expression: exp.Connect) -> str: 2113 start = self.sql(expression, "start") 2114 start = self.seg(f"START WITH {start}") if start else "" 2115 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2116 connect = self.sql(expression, "connect") 2117 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2118 return start + connect 2119 2120 def prior_sql(self, expression: exp.Prior) -> str: 2121 return f"PRIOR {self.sql(expression, 'this')}" 2122 2123 def join_sql(self, expression: exp.Join) -> str: 2124 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2125 side = None 2126 else: 2127 side = expression.side 2128 2129 op_sql = " ".join( 2130 op 2131 for op in ( 2132 expression.method, 2133 "GLOBAL" if expression.args.get("global") else None, 2134 side, 2135 expression.kind, 2136 expression.hint if self.JOIN_HINTS else None, 2137 ) 2138 if op 2139 ) 2140 match_cond = self.sql(expression, "match_condition") 2141 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2142 on_sql = self.sql(expression, "on") 2143 using = expression.args.get("using") 2144 2145 if not on_sql and using: 2146 on_sql = csv(*(self.sql(column) for column in using)) 2147 2148 this = expression.this 2149 this_sql = self.sql(this) 2150 2151 exprs = self.expressions(expression) 2152 if exprs: 2153 this_sql = f"{this_sql},{self.seg(exprs)}" 2154 2155 if on_sql: 2156 on_sql = self.indent(on_sql, skip_first=True) 2157 space = self.seg(" " * self.pad) if self.pretty else " " 2158 if using: 2159 on_sql = f"{space}USING ({on_sql})" 2160 else: 2161 on_sql = f"{space}ON {on_sql}" 2162 elif not op_sql: 2163 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2164 return f" {this_sql}" 2165 2166 return f", {this_sql}" 2167 2168 if op_sql != "STRAIGHT_JOIN": 2169 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2170 2171 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2172 2173 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2174 args = self.expressions(expression, flat=True) 2175 args = f"({args})" if len(args.split(",")) > 1 else args 2176 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2177 2178 def lateral_op(self, expression: exp.Lateral) -> str: 2179 cross_apply = expression.args.get("cross_apply") 2180 2181 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2182 if cross_apply is True: 2183 op = "INNER JOIN " 2184 elif cross_apply is False: 2185 op = "LEFT JOIN " 2186 else: 2187 op = "" 2188 2189 return f"{op}LATERAL" 2190 2191 def lateral_sql(self, expression: exp.Lateral) -> str: 2192 this = self.sql(expression, "this") 2193 2194 if expression.args.get("view"): 2195 alias = expression.args["alias"] 2196 columns = self.expressions(alias, key="columns", flat=True) 2197 table = f" {alias.name}" if alias.name else "" 2198 columns = f" AS {columns}" if columns else "" 2199 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2200 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2201 2202 alias = self.sql(expression, "alias") 2203 alias = f" AS {alias}" if alias else "" 2204 return f"{self.lateral_op(expression)} {this}{alias}" 2205 2206 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2207 this = self.sql(expression, "this") 2208 2209 args = [ 2210 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2211 for e in (expression.args.get(k) for k in ("offset", "expression")) 2212 if e 2213 ] 2214 2215 args_sql = ", ".join(self.sql(e) for e in args) 2216 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2217 expressions = self.expressions(expression, flat=True) 2218 expressions = f" BY {expressions}" if expressions else "" 2219 2220 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}" 2221 2222 def offset_sql(self, expression: exp.Offset) -> str: 2223 this = self.sql(expression, "this") 2224 value = expression.expression 2225 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2226 expressions = self.expressions(expression, flat=True) 2227 expressions = f" BY {expressions}" if expressions else "" 2228 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2229 2230 def setitem_sql(self, expression: exp.SetItem) -> str: 2231 kind = self.sql(expression, "kind") 2232 kind = f"{kind} " if kind else "" 2233 this = self.sql(expression, "this") 2234 expressions = self.expressions(expression) 2235 collate = self.sql(expression, "collate") 2236 collate = f" COLLATE {collate}" if collate else "" 2237 global_ = "GLOBAL " if expression.args.get("global") else "" 2238 return f"{global_}{kind}{this}{expressions}{collate}" 2239 2240 def set_sql(self, expression: exp.Set) -> str: 2241 expressions = ( 2242 f" {self.expressions(expression, flat=True)}" if expression.expressions else "" 2243 ) 2244 tag = " TAG" if expression.args.get("tag") else "" 2245 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2246 2247 def pragma_sql(self, expression: exp.Pragma) -> str: 2248 return f"PRAGMA {self.sql(expression, 'this')}" 2249 2250 def lock_sql(self, expression: exp.Lock) -> str: 2251 if not self.LOCKING_READS_SUPPORTED: 2252 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2253 return "" 2254 2255 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2256 expressions = self.expressions(expression, flat=True) 2257 expressions = f" OF {expressions}" if expressions else "" 2258 wait = expression.args.get("wait") 2259 2260 if wait is not None: 2261 if isinstance(wait, exp.Literal): 2262 wait = f" WAIT {self.sql(wait)}" 2263 else: 2264 wait = " NOWAIT" if wait else " SKIP LOCKED" 2265 2266 return f"{lock_type}{expressions}{wait or ''}" 2267 2268 def literal_sql(self, expression: exp.Literal) -> str: 2269 text = expression.this or "" 2270 if expression.is_string: 2271 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2272 return text 2273 2274 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2275 if self.dialect.ESCAPED_SEQUENCES: 2276 to_escaped = self.dialect.ESCAPED_SEQUENCES 2277 text = "".join( 2278 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2279 ) 2280 2281 return self._replace_line_breaks(text).replace( 2282 self.dialect.QUOTE_END, self._escaped_quote_end 2283 ) 2284 2285 def loaddata_sql(self, expression: exp.LoadData) -> str: 2286 local = " LOCAL" if expression.args.get("local") else "" 2287 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2288 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2289 this = f" INTO TABLE {self.sql(expression, 'this')}" 2290 partition = self.sql(expression, "partition") 2291 partition = f" {partition}" if partition else "" 2292 input_format = self.sql(expression, "input_format") 2293 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2294 serde = self.sql(expression, "serde") 2295 serde = f" SERDE {serde}" if serde else "" 2296 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2297 2298 def null_sql(self, *_) -> str: 2299 return "NULL" 2300 2301 def boolean_sql(self, expression: exp.Boolean) -> str: 2302 return "TRUE" if expression.this else "FALSE" 2303 2304 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2305 this = self.sql(expression, "this") 2306 this = f"{this} " if this else this 2307 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2308 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2309 2310 def withfill_sql(self, expression: exp.WithFill) -> str: 2311 from_sql = self.sql(expression, "from") 2312 from_sql = f" FROM {from_sql}" if from_sql else "" 2313 to_sql = self.sql(expression, "to") 2314 to_sql = f" TO {to_sql}" if to_sql else "" 2315 step_sql = self.sql(expression, "step") 2316 step_sql = f" STEP {step_sql}" if step_sql else "" 2317 interpolated_values = [ 2318 f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}" 2319 for named_expression in expression.args.get("interpolate") or [] 2320 ] 2321 interpolate = ( 2322 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2323 ) 2324 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2325 2326 def cluster_sql(self, expression: exp.Cluster) -> str: 2327 return self.op_expressions("CLUSTER BY", expression) 2328 2329 def distribute_sql(self, expression: exp.Distribute) -> str: 2330 return self.op_expressions("DISTRIBUTE BY", expression) 2331 2332 def sort_sql(self, expression: exp.Sort) -> str: 2333 return self.op_expressions("SORT BY", expression) 2334 2335 def ordered_sql(self, expression: exp.Ordered) -> str: 2336 desc = expression.args.get("desc") 2337 asc = not desc 2338 2339 nulls_first = expression.args.get("nulls_first") 2340 nulls_last = not nulls_first 2341 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2342 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2343 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2344 2345 this = self.sql(expression, "this") 2346 2347 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2348 nulls_sort_change = "" 2349 if nulls_first and ( 2350 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2351 ): 2352 nulls_sort_change = " NULLS FIRST" 2353 elif ( 2354 nulls_last 2355 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2356 and not nulls_are_last 2357 ): 2358 nulls_sort_change = " NULLS LAST" 2359 2360 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2361 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2362 window = expression.find_ancestor(exp.Window, exp.Select) 2363 if isinstance(window, exp.Window) and window.args.get("spec"): 2364 self.unsupported( 2365 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2366 ) 2367 nulls_sort_change = "" 2368 elif ( 2369 self.NULL_ORDERING_SUPPORTED is False 2370 and (isinstance(expression.find_ancestor(exp.AggFunc, exp.Select), exp.AggFunc)) 2371 and ( 2372 (asc and nulls_sort_change == " NULLS LAST") 2373 or (desc and nulls_sort_change == " NULLS FIRST") 2374 ) 2375 ): 2376 self.unsupported( 2377 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2378 ) 2379 nulls_sort_change = "" 2380 elif self.NULL_ORDERING_SUPPORTED is None: 2381 if expression.this.is_int: 2382 self.unsupported( 2383 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2384 ) 2385 elif not isinstance(expression.this, exp.Rand): 2386 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2387 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2388 nulls_sort_change = "" 2389 2390 with_fill = self.sql(expression, "with_fill") 2391 with_fill = f" {with_fill}" if with_fill else "" 2392 2393 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2394 2395 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2396 window_frame = self.sql(expression, "window_frame") 2397 window_frame = f"{window_frame} " if window_frame else "" 2398 2399 this = self.sql(expression, "this") 2400 2401 return f"{window_frame}{this}" 2402 2403 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2404 partition = self.partition_by_sql(expression) 2405 order = self.sql(expression, "order") 2406 measures = self.expressions(expression, key="measures") 2407 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2408 rows = self.sql(expression, "rows") 2409 rows = self.seg(rows) if rows else "" 2410 after = self.sql(expression, "after") 2411 after = self.seg(after) if after else "" 2412 pattern = self.sql(expression, "pattern") 2413 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2414 definition_sqls = [ 2415 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2416 for definition in expression.args.get("define", []) 2417 ] 2418 definitions = self.expressions(sqls=definition_sqls) 2419 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2420 body = "".join( 2421 ( 2422 partition, 2423 order, 2424 measures, 2425 rows, 2426 after, 2427 pattern, 2428 define, 2429 ) 2430 ) 2431 alias = self.sql(expression, "alias") 2432 alias = f" {alias}" if alias else "" 2433 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2434 2435 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2436 limit = expression.args.get("limit") 2437 2438 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2439 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2440 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2441 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2442 2443 return csv( 2444 *sqls, 2445 *[self.sql(join) for join in expression.args.get("joins") or []], 2446 self.sql(expression, "connect"), 2447 self.sql(expression, "match"), 2448 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2449 self.sql(expression, "prewhere"), 2450 self.sql(expression, "where"), 2451 self.sql(expression, "group"), 2452 self.sql(expression, "having"), 2453 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2454 self.sql(expression, "order"), 2455 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2456 *self.after_limit_modifiers(expression), 2457 self.options_modifier(expression), 2458 sep="", 2459 ) 2460 2461 def options_modifier(self, expression: exp.Expression) -> str: 2462 options = self.expressions(expression, key="options") 2463 return f" {options}" if options else "" 2464 2465 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2466 return "" 2467 2468 def offset_limit_modifiers( 2469 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2470 ) -> t.List[str]: 2471 return [ 2472 self.sql(expression, "offset") if fetch else self.sql(limit), 2473 self.sql(limit) if fetch else self.sql(expression, "offset"), 2474 ] 2475 2476 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2477 locks = self.expressions(expression, key="locks", sep=" ") 2478 locks = f" {locks}" if locks else "" 2479 return [locks, self.sql(expression, "sample")] 2480 2481 def select_sql(self, expression: exp.Select) -> str: 2482 into = expression.args.get("into") 2483 if not self.SUPPORTS_SELECT_INTO and into: 2484 into.pop() 2485 2486 hint = self.sql(expression, "hint") 2487 distinct = self.sql(expression, "distinct") 2488 distinct = f" {distinct}" if distinct else "" 2489 kind = self.sql(expression, "kind") 2490 2491 limit = expression.args.get("limit") 2492 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2493 top = self.limit_sql(limit, top=True) 2494 limit.pop() 2495 else: 2496 top = "" 2497 2498 expressions = self.expressions(expression) 2499 2500 if kind: 2501 if kind in self.SELECT_KINDS: 2502 kind = f" AS {kind}" 2503 else: 2504 if kind == "STRUCT": 2505 expressions = self.expressions( 2506 sqls=[ 2507 self.sql( 2508 exp.Struct( 2509 expressions=[ 2510 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2511 if isinstance(e, exp.Alias) 2512 else e 2513 for e in expression.expressions 2514 ] 2515 ) 2516 ) 2517 ] 2518 ) 2519 kind = "" 2520 2521 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2522 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2523 2524 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2525 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2526 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2527 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2528 sql = self.query_modifiers( 2529 expression, 2530 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2531 self.sql(expression, "into", comment=False), 2532 self.sql(expression, "from", comment=False), 2533 ) 2534 2535 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2536 if expression.args.get("with"): 2537 sql = self.maybe_comment(sql, expression) 2538 expression.pop_comments() 2539 2540 sql = self.prepend_ctes(expression, sql) 2541 2542 if not self.SUPPORTS_SELECT_INTO and into: 2543 if into.args.get("temporary"): 2544 table_kind = " TEMPORARY" 2545 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2546 table_kind = " UNLOGGED" 2547 else: 2548 table_kind = "" 2549 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2550 2551 return sql 2552 2553 def schema_sql(self, expression: exp.Schema) -> str: 2554 this = self.sql(expression, "this") 2555 sql = self.schema_columns_sql(expression) 2556 return f"{this} {sql}" if this and sql else this or sql 2557 2558 def schema_columns_sql(self, expression: exp.Schema) -> str: 2559 if expression.expressions: 2560 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2561 return "" 2562 2563 def star_sql(self, expression: exp.Star) -> str: 2564 except_ = self.expressions(expression, key="except", flat=True) 2565 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2566 replace = self.expressions(expression, key="replace", flat=True) 2567 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2568 rename = self.expressions(expression, key="rename", flat=True) 2569 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2570 return f"*{except_}{replace}{rename}" 2571 2572 def parameter_sql(self, expression: exp.Parameter) -> str: 2573 this = self.sql(expression, "this") 2574 return f"{self.PARAMETER_TOKEN}{this}" 2575 2576 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2577 this = self.sql(expression, "this") 2578 kind = expression.text("kind") 2579 if kind: 2580 kind = f"{kind}." 2581 return f"@@{kind}{this}" 2582 2583 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2584 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2585 2586 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2587 alias = self.sql(expression, "alias") 2588 alias = f"{sep}{alias}" if alias else "" 2589 sample = self.sql(expression, "sample") 2590 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2591 alias = f"{sample}{alias}" 2592 2593 # Set to None so it's not generated again by self.query_modifiers() 2594 expression.set("sample", None) 2595 2596 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2597 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2598 return self.prepend_ctes(expression, sql) 2599 2600 def qualify_sql(self, expression: exp.Qualify) -> str: 2601 this = self.indent(self.sql(expression, "this")) 2602 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2603 2604 def unnest_sql(self, expression: exp.Unnest) -> str: 2605 args = self.expressions(expression, flat=True) 2606 2607 alias = expression.args.get("alias") 2608 offset = expression.args.get("offset") 2609 2610 if self.UNNEST_WITH_ORDINALITY: 2611 if alias and isinstance(offset, exp.Expression): 2612 alias.append("columns", offset) 2613 2614 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2615 columns = alias.columns 2616 alias = self.sql(columns[0]) if columns else "" 2617 else: 2618 alias = self.sql(alias) 2619 2620 alias = f" AS {alias}" if alias else alias 2621 if self.UNNEST_WITH_ORDINALITY: 2622 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2623 else: 2624 if isinstance(offset, exp.Expression): 2625 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2626 elif offset: 2627 suffix = f"{alias} WITH OFFSET" 2628 else: 2629 suffix = alias 2630 2631 return f"UNNEST({args}){suffix}" 2632 2633 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2634 return "" 2635 2636 def where_sql(self, expression: exp.Where) -> str: 2637 this = self.indent(self.sql(expression, "this")) 2638 return f"{self.seg('WHERE')}{self.sep()}{this}" 2639 2640 def window_sql(self, expression: exp.Window) -> str: 2641 this = self.sql(expression, "this") 2642 partition = self.partition_by_sql(expression) 2643 order = expression.args.get("order") 2644 order = self.order_sql(order, flat=True) if order else "" 2645 spec = self.sql(expression, "spec") 2646 alias = self.sql(expression, "alias") 2647 over = self.sql(expression, "over") or "OVER" 2648 2649 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2650 2651 first = expression.args.get("first") 2652 if first is None: 2653 first = "" 2654 else: 2655 first = "FIRST" if first else "LAST" 2656 2657 if not partition and not order and not spec and alias: 2658 return f"{this} {alias}" 2659 2660 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2661 return f"{this} ({args})" 2662 2663 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2664 partition = self.expressions(expression, key="partition_by", flat=True) 2665 return f"PARTITION BY {partition}" if partition else "" 2666 2667 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2668 kind = self.sql(expression, "kind") 2669 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2670 end = ( 2671 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2672 or "CURRENT ROW" 2673 ) 2674 return f"{kind} BETWEEN {start} AND {end}" 2675 2676 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2677 this = self.sql(expression, "this") 2678 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2679 return f"{this} WITHIN GROUP ({expression_sql})" 2680 2681 def between_sql(self, expression: exp.Between) -> str: 2682 this = self.sql(expression, "this") 2683 low = self.sql(expression, "low") 2684 high = self.sql(expression, "high") 2685 return f"{this} BETWEEN {low} AND {high}" 2686 2687 def bracket_offset_expressions( 2688 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2689 ) -> t.List[exp.Expression]: 2690 return apply_index_offset( 2691 expression.this, 2692 expression.expressions, 2693 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2694 ) 2695 2696 def bracket_sql(self, expression: exp.Bracket) -> str: 2697 expressions = self.bracket_offset_expressions(expression) 2698 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2699 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2700 2701 def all_sql(self, expression: exp.All) -> str: 2702 return f"ALL {self.wrap(expression)}" 2703 2704 def any_sql(self, expression: exp.Any) -> str: 2705 this = self.sql(expression, "this") 2706 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2707 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2708 this = self.wrap(this) 2709 return f"ANY{this}" 2710 return f"ANY {this}" 2711 2712 def exists_sql(self, expression: exp.Exists) -> str: 2713 return f"EXISTS{self.wrap(expression)}" 2714 2715 def case_sql(self, expression: exp.Case) -> str: 2716 this = self.sql(expression, "this") 2717 statements = [f"CASE {this}" if this else "CASE"] 2718 2719 for e in expression.args["ifs"]: 2720 statements.append(f"WHEN {self.sql(e, 'this')}") 2721 statements.append(f"THEN {self.sql(e, 'true')}") 2722 2723 default = self.sql(expression, "default") 2724 2725 if default: 2726 statements.append(f"ELSE {default}") 2727 2728 statements.append("END") 2729 2730 if self.pretty and self.too_wide(statements): 2731 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2732 2733 return " ".join(statements) 2734 2735 def constraint_sql(self, expression: exp.Constraint) -> str: 2736 this = self.sql(expression, "this") 2737 expressions = self.expressions(expression, flat=True) 2738 return f"CONSTRAINT {this} {expressions}" 2739 2740 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2741 order = expression.args.get("order") 2742 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2743 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2744 2745 def extract_sql(self, expression: exp.Extract) -> str: 2746 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2747 expression_sql = self.sql(expression, "expression") 2748 return f"EXTRACT({this} FROM {expression_sql})" 2749 2750 def trim_sql(self, expression: exp.Trim) -> str: 2751 trim_type = self.sql(expression, "position") 2752 2753 if trim_type == "LEADING": 2754 func_name = "LTRIM" 2755 elif trim_type == "TRAILING": 2756 func_name = "RTRIM" 2757 else: 2758 func_name = "TRIM" 2759 2760 return self.func(func_name, expression.this, expression.expression) 2761 2762 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2763 args = expression.expressions 2764 if isinstance(expression, exp.ConcatWs): 2765 args = args[1:] # Skip the delimiter 2766 2767 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2768 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2769 2770 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2771 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2772 2773 return args 2774 2775 def concat_sql(self, expression: exp.Concat) -> str: 2776 expressions = self.convert_concat_args(expression) 2777 2778 # Some dialects don't allow a single-argument CONCAT call 2779 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2780 return self.sql(expressions[0]) 2781 2782 return self.func("CONCAT", *expressions) 2783 2784 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2785 return self.func( 2786 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2787 ) 2788 2789 def check_sql(self, expression: exp.Check) -> str: 2790 this = self.sql(expression, key="this") 2791 return f"CHECK ({this})" 2792 2793 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2794 expressions = self.expressions(expression, flat=True) 2795 reference = self.sql(expression, "reference") 2796 reference = f" {reference}" if reference else "" 2797 delete = self.sql(expression, "delete") 2798 delete = f" ON DELETE {delete}" if delete else "" 2799 update = self.sql(expression, "update") 2800 update = f" ON UPDATE {update}" if update else "" 2801 return f"FOREIGN KEY ({expressions}){reference}{delete}{update}" 2802 2803 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2804 expressions = self.expressions(expression, flat=True) 2805 options = self.expressions(expression, key="options", flat=True, sep=" ") 2806 options = f" {options}" if options else "" 2807 return f"PRIMARY KEY ({expressions}){options}" 2808 2809 def if_sql(self, expression: exp.If) -> str: 2810 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2811 2812 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2813 modifier = expression.args.get("modifier") 2814 modifier = f" {modifier}" if modifier else "" 2815 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2816 2817 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2818 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2819 2820 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2821 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2822 2823 if expression.args.get("escape"): 2824 path = self.escape_str(path) 2825 2826 if self.QUOTE_JSON_PATH: 2827 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2828 2829 return path 2830 2831 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2832 if isinstance(expression, exp.JSONPathPart): 2833 transform = self.TRANSFORMS.get(expression.__class__) 2834 if not callable(transform): 2835 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2836 return "" 2837 2838 return transform(self, expression) 2839 2840 if isinstance(expression, int): 2841 return str(expression) 2842 2843 if self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2844 escaped = expression.replace("'", "\\'") 2845 escaped = f"\\'{expression}\\'" 2846 else: 2847 escaped = expression.replace('"', '\\"') 2848 escaped = f'"{escaped}"' 2849 2850 return escaped 2851 2852 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2853 return f"{self.sql(expression, 'this')} FORMAT JSON" 2854 2855 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2856 null_handling = expression.args.get("null_handling") 2857 null_handling = f" {null_handling}" if null_handling else "" 2858 2859 unique_keys = expression.args.get("unique_keys") 2860 if unique_keys is not None: 2861 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2862 else: 2863 unique_keys = "" 2864 2865 return_type = self.sql(expression, "return_type") 2866 return_type = f" RETURNING {return_type}" if return_type else "" 2867 encoding = self.sql(expression, "encoding") 2868 encoding = f" ENCODING {encoding}" if encoding else "" 2869 2870 return self.func( 2871 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2872 *expression.expressions, 2873 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2874 ) 2875 2876 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2877 return self.jsonobject_sql(expression) 2878 2879 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2880 null_handling = expression.args.get("null_handling") 2881 null_handling = f" {null_handling}" if null_handling else "" 2882 return_type = self.sql(expression, "return_type") 2883 return_type = f" RETURNING {return_type}" if return_type else "" 2884 strict = " STRICT" if expression.args.get("strict") else "" 2885 return self.func( 2886 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2887 ) 2888 2889 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2890 this = self.sql(expression, "this") 2891 order = self.sql(expression, "order") 2892 null_handling = expression.args.get("null_handling") 2893 null_handling = f" {null_handling}" if null_handling else "" 2894 return_type = self.sql(expression, "return_type") 2895 return_type = f" RETURNING {return_type}" if return_type else "" 2896 strict = " STRICT" if expression.args.get("strict") else "" 2897 return self.func( 2898 "JSON_ARRAYAGG", 2899 this, 2900 suffix=f"{order}{null_handling}{return_type}{strict})", 2901 ) 2902 2903 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2904 path = self.sql(expression, "path") 2905 path = f" PATH {path}" if path else "" 2906 nested_schema = self.sql(expression, "nested_schema") 2907 2908 if nested_schema: 2909 return f"NESTED{path} {nested_schema}" 2910 2911 this = self.sql(expression, "this") 2912 kind = self.sql(expression, "kind") 2913 kind = f" {kind}" if kind else "" 2914 return f"{this}{kind}{path}" 2915 2916 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 2917 return self.func("COLUMNS", *expression.expressions) 2918 2919 def jsontable_sql(self, expression: exp.JSONTable) -> str: 2920 this = self.sql(expression, "this") 2921 path = self.sql(expression, "path") 2922 path = f", {path}" if path else "" 2923 error_handling = expression.args.get("error_handling") 2924 error_handling = f" {error_handling}" if error_handling else "" 2925 empty_handling = expression.args.get("empty_handling") 2926 empty_handling = f" {empty_handling}" if empty_handling else "" 2927 schema = self.sql(expression, "schema") 2928 return self.func( 2929 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 2930 ) 2931 2932 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 2933 this = self.sql(expression, "this") 2934 kind = self.sql(expression, "kind") 2935 path = self.sql(expression, "path") 2936 path = f" {path}" if path else "" 2937 as_json = " AS JSON" if expression.args.get("as_json") else "" 2938 return f"{this} {kind}{path}{as_json}" 2939 2940 def openjson_sql(self, expression: exp.OpenJSON) -> str: 2941 this = self.sql(expression, "this") 2942 path = self.sql(expression, "path") 2943 path = f", {path}" if path else "" 2944 expressions = self.expressions(expression) 2945 with_ = ( 2946 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 2947 if expressions 2948 else "" 2949 ) 2950 return f"OPENJSON({this}{path}){with_}" 2951 2952 def in_sql(self, expression: exp.In) -> str: 2953 query = expression.args.get("query") 2954 unnest = expression.args.get("unnest") 2955 field = expression.args.get("field") 2956 is_global = " GLOBAL" if expression.args.get("is_global") else "" 2957 2958 if query: 2959 in_sql = self.sql(query) 2960 elif unnest: 2961 in_sql = self.in_unnest_op(unnest) 2962 elif field: 2963 in_sql = self.sql(field) 2964 else: 2965 in_sql = f"({self.expressions(expression, flat=True)})" 2966 2967 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 2968 2969 def in_unnest_op(self, unnest: exp.Unnest) -> str: 2970 return f"(SELECT {self.sql(unnest)})" 2971 2972 def interval_sql(self, expression: exp.Interval) -> str: 2973 unit = self.sql(expression, "unit") 2974 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 2975 unit = self.TIME_PART_SINGULARS.get(unit, unit) 2976 unit = f" {unit}" if unit else "" 2977 2978 if self.SINGLE_STRING_INTERVAL: 2979 this = expression.this.name if expression.this else "" 2980 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 2981 2982 this = self.sql(expression, "this") 2983 if this: 2984 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 2985 this = f" {this}" if unwrapped else f" ({this})" 2986 2987 return f"INTERVAL{this}{unit}" 2988 2989 def return_sql(self, expression: exp.Return) -> str: 2990 return f"RETURN {self.sql(expression, 'this')}" 2991 2992 def reference_sql(self, expression: exp.Reference) -> str: 2993 this = self.sql(expression, "this") 2994 expressions = self.expressions(expression, flat=True) 2995 expressions = f"({expressions})" if expressions else "" 2996 options = self.expressions(expression, key="options", flat=True, sep=" ") 2997 options = f" {options}" if options else "" 2998 return f"REFERENCES {this}{expressions}{options}" 2999 3000 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3001 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3002 parent = expression.parent 3003 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3004 return self.func( 3005 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3006 ) 3007 3008 def paren_sql(self, expression: exp.Paren) -> str: 3009 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3010 return f"({sql}{self.seg(')', sep='')}" 3011 3012 def neg_sql(self, expression: exp.Neg) -> str: 3013 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3014 this_sql = self.sql(expression, "this") 3015 sep = " " if this_sql[0] == "-" else "" 3016 return f"-{sep}{this_sql}" 3017 3018 def not_sql(self, expression: exp.Not) -> str: 3019 return f"NOT {self.sql(expression, 'this')}" 3020 3021 def alias_sql(self, expression: exp.Alias) -> str: 3022 alias = self.sql(expression, "alias") 3023 alias = f" AS {alias}" if alias else "" 3024 return f"{self.sql(expression, 'this')}{alias}" 3025 3026 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3027 alias = expression.args["alias"] 3028 3029 identifier_alias = isinstance(alias, exp.Identifier) 3030 literal_alias = isinstance(alias, exp.Literal) 3031 3032 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3033 alias.replace(exp.Literal.string(alias.output_name)) 3034 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3035 alias.replace(exp.to_identifier(alias.output_name)) 3036 3037 return self.alias_sql(expression) 3038 3039 def aliases_sql(self, expression: exp.Aliases) -> str: 3040 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3041 3042 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3043 this = self.sql(expression, "this") 3044 index = self.sql(expression, "expression") 3045 return f"{this} AT {index}" 3046 3047 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3048 this = self.sql(expression, "this") 3049 zone = self.sql(expression, "zone") 3050 return f"{this} AT TIME ZONE {zone}" 3051 3052 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3053 this = self.sql(expression, "this") 3054 zone = self.sql(expression, "zone") 3055 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3056 3057 def add_sql(self, expression: exp.Add) -> str: 3058 return self.binary(expression, "+") 3059 3060 def and_sql( 3061 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3062 ) -> str: 3063 return self.connector_sql(expression, "AND", stack) 3064 3065 def or_sql( 3066 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3067 ) -> str: 3068 return self.connector_sql(expression, "OR", stack) 3069 3070 def xor_sql( 3071 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3072 ) -> str: 3073 return self.connector_sql(expression, "XOR", stack) 3074 3075 def connector_sql( 3076 self, 3077 expression: exp.Connector, 3078 op: str, 3079 stack: t.Optional[t.List[str | exp.Expression]] = None, 3080 ) -> str: 3081 if stack is not None: 3082 if expression.expressions: 3083 stack.append(self.expressions(expression, sep=f" {op} ")) 3084 else: 3085 stack.append(expression.right) 3086 if expression.comments and self.comments: 3087 for comment in expression.comments: 3088 if comment: 3089 op += f" /*{self.pad_comment(comment)}*/" 3090 stack.extend((op, expression.left)) 3091 return op 3092 3093 stack = [expression] 3094 sqls: t.List[str] = [] 3095 ops = set() 3096 3097 while stack: 3098 node = stack.pop() 3099 if isinstance(node, exp.Connector): 3100 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3101 else: 3102 sql = self.sql(node) 3103 if sqls and sqls[-1] in ops: 3104 sqls[-1] += f" {sql}" 3105 else: 3106 sqls.append(sql) 3107 3108 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3109 return sep.join(sqls) 3110 3111 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3112 return self.binary(expression, "&") 3113 3114 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3115 return self.binary(expression, "<<") 3116 3117 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3118 return f"~{self.sql(expression, 'this')}" 3119 3120 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3121 return self.binary(expression, "|") 3122 3123 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3124 return self.binary(expression, ">>") 3125 3126 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3127 return self.binary(expression, "^") 3128 3129 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3130 format_sql = self.sql(expression, "format") 3131 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3132 to_sql = self.sql(expression, "to") 3133 to_sql = f" {to_sql}" if to_sql else "" 3134 action = self.sql(expression, "action") 3135 action = f" {action}" if action else "" 3136 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})" 3137 3138 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3139 zone = self.sql(expression, "this") 3140 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3141 3142 def collate_sql(self, expression: exp.Collate) -> str: 3143 if self.COLLATE_IS_FUNC: 3144 return self.function_fallback_sql(expression) 3145 return self.binary(expression, "COLLATE") 3146 3147 def command_sql(self, expression: exp.Command) -> str: 3148 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3149 3150 def comment_sql(self, expression: exp.Comment) -> str: 3151 this = self.sql(expression, "this") 3152 kind = expression.args["kind"] 3153 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3154 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3155 expression_sql = self.sql(expression, "expression") 3156 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3157 3158 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3159 this = self.sql(expression, "this") 3160 delete = " DELETE" if expression.args.get("delete") else "" 3161 recompress = self.sql(expression, "recompress") 3162 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3163 to_disk = self.sql(expression, "to_disk") 3164 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3165 to_volume = self.sql(expression, "to_volume") 3166 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3167 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3168 3169 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3170 where = self.sql(expression, "where") 3171 group = self.sql(expression, "group") 3172 aggregates = self.expressions(expression, key="aggregates") 3173 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3174 3175 if not (where or group or aggregates) and len(expression.expressions) == 1: 3176 return f"TTL {self.expressions(expression, flat=True)}" 3177 3178 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3179 3180 def transaction_sql(self, expression: exp.Transaction) -> str: 3181 return "BEGIN" 3182 3183 def commit_sql(self, expression: exp.Commit) -> str: 3184 chain = expression.args.get("chain") 3185 if chain is not None: 3186 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3187 3188 return f"COMMIT{chain or ''}" 3189 3190 def rollback_sql(self, expression: exp.Rollback) -> str: 3191 savepoint = expression.args.get("savepoint") 3192 savepoint = f" TO {savepoint}" if savepoint else "" 3193 return f"ROLLBACK{savepoint}" 3194 3195 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3196 this = self.sql(expression, "this") 3197 3198 dtype = self.sql(expression, "dtype") 3199 if dtype: 3200 collate = self.sql(expression, "collate") 3201 collate = f" COLLATE {collate}" if collate else "" 3202 using = self.sql(expression, "using") 3203 using = f" USING {using}" if using else "" 3204 return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}" 3205 3206 default = self.sql(expression, "default") 3207 if default: 3208 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3209 3210 comment = self.sql(expression, "comment") 3211 if comment: 3212 return f"ALTER COLUMN {this} COMMENT {comment}" 3213 3214 allow_null = expression.args.get("allow_null") 3215 drop = expression.args.get("drop") 3216 3217 if not drop and not allow_null: 3218 self.unsupported("Unsupported ALTER COLUMN syntax") 3219 3220 if allow_null is not None: 3221 keyword = "DROP" if drop else "SET" 3222 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3223 3224 return f"ALTER COLUMN {this} DROP DEFAULT" 3225 3226 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3227 this = self.sql(expression, "this") 3228 if not isinstance(expression.this, exp.Var): 3229 this = f"KEY DISTKEY {this}" 3230 return f"ALTER DISTSTYLE {this}" 3231 3232 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3233 compound = " COMPOUND" if expression.args.get("compound") else "" 3234 this = self.sql(expression, "this") 3235 expressions = self.expressions(expression, flat=True) 3236 expressions = f"({expressions})" if expressions else "" 3237 return f"ALTER{compound} SORTKEY {this or expressions}" 3238 3239 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3240 if not self.RENAME_TABLE_WITH_DB: 3241 # Remove db from tables 3242 expression = expression.transform( 3243 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3244 ).assert_is(exp.AlterRename) 3245 this = self.sql(expression, "this") 3246 return f"RENAME TO {this}" 3247 3248 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3249 exists = " IF EXISTS" if expression.args.get("exists") else "" 3250 old_column = self.sql(expression, "this") 3251 new_column = self.sql(expression, "to") 3252 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3253 3254 def alterset_sql(self, expression: exp.AlterSet) -> str: 3255 exprs = self.expressions(expression, flat=True) 3256 return f"SET {exprs}" 3257 3258 def alter_sql(self, expression: exp.Alter) -> str: 3259 actions = expression.args["actions"] 3260 3261 if isinstance(actions[0], exp.ColumnDef): 3262 actions = self.add_column_sql(expression) 3263 elif isinstance(actions[0], exp.Schema): 3264 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3265 elif isinstance(actions[0], exp.Delete): 3266 actions = self.expressions(expression, key="actions", flat=True) 3267 elif isinstance(actions[0], exp.Query): 3268 actions = "AS " + self.expressions(expression, key="actions") 3269 else: 3270 actions = self.expressions(expression, key="actions", flat=True) 3271 3272 exists = " IF EXISTS" if expression.args.get("exists") else "" 3273 on_cluster = self.sql(expression, "cluster") 3274 on_cluster = f" {on_cluster}" if on_cluster else "" 3275 only = " ONLY" if expression.args.get("only") else "" 3276 options = self.expressions(expression, key="options") 3277 options = f", {options}" if options else "" 3278 kind = self.sql(expression, "kind") 3279 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3280 3281 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3282 3283 def add_column_sql(self, expression: exp.Alter) -> str: 3284 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3285 return self.expressions( 3286 expression, 3287 key="actions", 3288 prefix="ADD COLUMN ", 3289 skip_first=True, 3290 ) 3291 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3292 3293 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3294 expressions = self.expressions(expression) 3295 exists = " IF EXISTS " if expression.args.get("exists") else " " 3296 return f"DROP{exists}{expressions}" 3297 3298 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3299 return f"ADD {self.expressions(expression)}" 3300 3301 def distinct_sql(self, expression: exp.Distinct) -> str: 3302 this = self.expressions(expression, flat=True) 3303 3304 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3305 case = exp.case() 3306 for arg in expression.expressions: 3307 case = case.when(arg.is_(exp.null()), exp.null()) 3308 this = self.sql(case.else_(f"({this})")) 3309 3310 this = f" {this}" if this else "" 3311 3312 on = self.sql(expression, "on") 3313 on = f" ON {on}" if on else "" 3314 return f"DISTINCT{this}{on}" 3315 3316 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3317 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3318 3319 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3320 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3321 3322 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3323 this_sql = self.sql(expression, "this") 3324 expression_sql = self.sql(expression, "expression") 3325 kind = "MAX" if expression.args.get("max") else "MIN" 3326 return f"{this_sql} HAVING {kind} {expression_sql}" 3327 3328 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3329 return self.sql( 3330 exp.Cast( 3331 this=exp.Div(this=expression.this, expression=expression.expression), 3332 to=exp.DataType(this=exp.DataType.Type.INT), 3333 ) 3334 ) 3335 3336 def dpipe_sql(self, expression: exp.DPipe) -> str: 3337 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3338 return self.func( 3339 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3340 ) 3341 return self.binary(expression, "||") 3342 3343 def div_sql(self, expression: exp.Div) -> str: 3344 l, r = expression.left, expression.right 3345 3346 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3347 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3348 3349 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3350 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3351 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3352 3353 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3354 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3355 return self.sql( 3356 exp.cast( 3357 l / r, 3358 to=exp.DataType.Type.BIGINT, 3359 ) 3360 ) 3361 3362 return self.binary(expression, "/") 3363 3364 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3365 return self.binary(expression, "OVERLAPS") 3366 3367 def distance_sql(self, expression: exp.Distance) -> str: 3368 return self.binary(expression, "<->") 3369 3370 def dot_sql(self, expression: exp.Dot) -> str: 3371 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3372 3373 def eq_sql(self, expression: exp.EQ) -> str: 3374 return self.binary(expression, "=") 3375 3376 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3377 return self.binary(expression, ":=") 3378 3379 def escape_sql(self, expression: exp.Escape) -> str: 3380 return self.binary(expression, "ESCAPE") 3381 3382 def glob_sql(self, expression: exp.Glob) -> str: 3383 return self.binary(expression, "GLOB") 3384 3385 def gt_sql(self, expression: exp.GT) -> str: 3386 return self.binary(expression, ">") 3387 3388 def gte_sql(self, expression: exp.GTE) -> str: 3389 return self.binary(expression, ">=") 3390 3391 def ilike_sql(self, expression: exp.ILike) -> str: 3392 return self.binary(expression, "ILIKE") 3393 3394 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3395 return self.binary(expression, "ILIKE ANY") 3396 3397 def is_sql(self, expression: exp.Is) -> str: 3398 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3399 return self.sql( 3400 expression.this if expression.expression.this else exp.not_(expression.this) 3401 ) 3402 return self.binary(expression, "IS") 3403 3404 def like_sql(self, expression: exp.Like) -> str: 3405 return self.binary(expression, "LIKE") 3406 3407 def likeany_sql(self, expression: exp.LikeAny) -> str: 3408 return self.binary(expression, "LIKE ANY") 3409 3410 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3411 return self.binary(expression, "SIMILAR TO") 3412 3413 def lt_sql(self, expression: exp.LT) -> str: 3414 return self.binary(expression, "<") 3415 3416 def lte_sql(self, expression: exp.LTE) -> str: 3417 return self.binary(expression, "<=") 3418 3419 def mod_sql(self, expression: exp.Mod) -> str: 3420 return self.binary(expression, "%") 3421 3422 def mul_sql(self, expression: exp.Mul) -> str: 3423 return self.binary(expression, "*") 3424 3425 def neq_sql(self, expression: exp.NEQ) -> str: 3426 return self.binary(expression, "<>") 3427 3428 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3429 return self.binary(expression, "IS NOT DISTINCT FROM") 3430 3431 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3432 return self.binary(expression, "IS DISTINCT FROM") 3433 3434 def slice_sql(self, expression: exp.Slice) -> str: 3435 return self.binary(expression, ":") 3436 3437 def sub_sql(self, expression: exp.Sub) -> str: 3438 return self.binary(expression, "-") 3439 3440 def trycast_sql(self, expression: exp.TryCast) -> str: 3441 return self.cast_sql(expression, safe_prefix="TRY_") 3442 3443 def try_sql(self, expression: exp.Try) -> str: 3444 if not self.TRY_SUPPORTED: 3445 self.unsupported("Unsupported TRY function") 3446 return self.sql(expression, "this") 3447 3448 return self.func("TRY", expression.this) 3449 3450 def log_sql(self, expression: exp.Log) -> str: 3451 this = expression.this 3452 expr = expression.expression 3453 3454 if self.dialect.LOG_BASE_FIRST is False: 3455 this, expr = expr, this 3456 elif self.dialect.LOG_BASE_FIRST is None and expr: 3457 if this.name in ("2", "10"): 3458 return self.func(f"LOG{this.name}", expr) 3459 3460 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3461 3462 return self.func("LOG", this, expr) 3463 3464 def use_sql(self, expression: exp.Use) -> str: 3465 kind = self.sql(expression, "kind") 3466 kind = f" {kind}" if kind else "" 3467 this = self.sql(expression, "this") 3468 this = f" {this}" if this else "" 3469 return f"USE{kind}{this}" 3470 3471 def binary(self, expression: exp.Binary, op: str) -> str: 3472 sqls: t.List[str] = [] 3473 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3474 binary_type = type(expression) 3475 3476 while stack: 3477 node = stack.pop() 3478 3479 if type(node) is binary_type: 3480 op_func = node.args.get("operator") 3481 if op_func: 3482 op = f"OPERATOR({self.sql(op_func)})" 3483 3484 stack.append(node.right) 3485 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3486 stack.append(node.left) 3487 else: 3488 sqls.append(self.sql(node)) 3489 3490 return "".join(sqls) 3491 3492 def function_fallback_sql(self, expression: exp.Func) -> str: 3493 args = [] 3494 3495 for key in expression.arg_types: 3496 arg_value = expression.args.get(key) 3497 3498 if isinstance(arg_value, list): 3499 for value in arg_value: 3500 args.append(value) 3501 elif arg_value is not None: 3502 args.append(arg_value) 3503 3504 if self.normalize_functions: 3505 name = expression.sql_name() 3506 else: 3507 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3508 3509 return self.func(name, *args) 3510 3511 def func( 3512 self, 3513 name: str, 3514 *args: t.Optional[exp.Expression | str], 3515 prefix: str = "(", 3516 suffix: str = ")", 3517 normalize: bool = True, 3518 ) -> str: 3519 name = self.normalize_func(name) if normalize else name 3520 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3521 3522 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3523 arg_sqls = tuple( 3524 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3525 ) 3526 if self.pretty and self.too_wide(arg_sqls): 3527 return self.indent( 3528 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3529 ) 3530 return sep.join(arg_sqls) 3531 3532 def too_wide(self, args: t.Iterable) -> bool: 3533 return sum(len(arg) for arg in args) > self.max_text_width 3534 3535 def format_time( 3536 self, 3537 expression: exp.Expression, 3538 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3539 inverse_time_trie: t.Optional[t.Dict] = None, 3540 ) -> t.Optional[str]: 3541 return format_time( 3542 self.sql(expression, "format"), 3543 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3544 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3545 ) 3546 3547 def expressions( 3548 self, 3549 expression: t.Optional[exp.Expression] = None, 3550 key: t.Optional[str] = None, 3551 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3552 flat: bool = False, 3553 indent: bool = True, 3554 skip_first: bool = False, 3555 skip_last: bool = False, 3556 sep: str = ", ", 3557 prefix: str = "", 3558 dynamic: bool = False, 3559 new_line: bool = False, 3560 ) -> str: 3561 expressions = expression.args.get(key or "expressions") if expression else sqls 3562 3563 if not expressions: 3564 return "" 3565 3566 if flat: 3567 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3568 3569 num_sqls = len(expressions) 3570 result_sqls = [] 3571 3572 for i, e in enumerate(expressions): 3573 sql = self.sql(e, comment=False) 3574 if not sql: 3575 continue 3576 3577 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3578 3579 if self.pretty: 3580 if self.leading_comma: 3581 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3582 else: 3583 result_sqls.append( 3584 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3585 ) 3586 else: 3587 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3588 3589 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3590 if new_line: 3591 result_sqls.insert(0, "") 3592 result_sqls.append("") 3593 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3594 else: 3595 result_sql = "".join(result_sqls) 3596 3597 return ( 3598 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3599 if indent 3600 else result_sql 3601 ) 3602 3603 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3604 flat = flat or isinstance(expression.parent, exp.Properties) 3605 expressions_sql = self.expressions(expression, flat=flat) 3606 if flat: 3607 return f"{op} {expressions_sql}" 3608 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3609 3610 def naked_property(self, expression: exp.Property) -> str: 3611 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3612 if not property_name: 3613 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3614 return f"{property_name} {self.sql(expression, 'this')}" 3615 3616 def tag_sql(self, expression: exp.Tag) -> str: 3617 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3618 3619 def token_sql(self, token_type: TokenType) -> str: 3620 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3621 3622 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3623 this = self.sql(expression, "this") 3624 expressions = self.no_identify(self.expressions, expression) 3625 expressions = ( 3626 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3627 ) 3628 return f"{this}{expressions}" if expressions.strip() != "" else this 3629 3630 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3631 this = self.sql(expression, "this") 3632 expressions = self.expressions(expression, flat=True) 3633 return f"{this}({expressions})" 3634 3635 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3636 return self.binary(expression, "=>") 3637 3638 def when_sql(self, expression: exp.When) -> str: 3639 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3640 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3641 condition = self.sql(expression, "condition") 3642 condition = f" AND {condition}" if condition else "" 3643 3644 then_expression = expression.args.get("then") 3645 if isinstance(then_expression, exp.Insert): 3646 this = self.sql(then_expression, "this") 3647 this = f"INSERT {this}" if this else "INSERT" 3648 then = self.sql(then_expression, "expression") 3649 then = f"{this} VALUES {then}" if then else this 3650 elif isinstance(then_expression, exp.Update): 3651 if isinstance(then_expression.args.get("expressions"), exp.Star): 3652 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3653 else: 3654 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3655 else: 3656 then = self.sql(then_expression) 3657 return f"WHEN {matched}{source}{condition} THEN {then}" 3658 3659 def merge_sql(self, expression: exp.Merge) -> str: 3660 table = expression.this 3661 table_alias = "" 3662 3663 hints = table.args.get("hints") 3664 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3665 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3666 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3667 3668 this = self.sql(table) 3669 using = f"USING {self.sql(expression, 'using')}" 3670 on = f"ON {self.sql(expression, 'on')}" 3671 expressions = self.expressions(expression, sep=" ", indent=False) 3672 returning = self.sql(expression, "returning") 3673 if returning: 3674 expressions = f"{expressions}{returning}" 3675 3676 sep = self.sep() 3677 3678 return self.prepend_ctes( 3679 expression, 3680 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}", 3681 ) 3682 3683 @unsupported_args("format") 3684 def tochar_sql(self, expression: exp.ToChar) -> str: 3685 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3686 3687 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3688 if not self.SUPPORTS_TO_NUMBER: 3689 self.unsupported("Unsupported TO_NUMBER function") 3690 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3691 3692 fmt = expression.args.get("format") 3693 if not fmt: 3694 self.unsupported("Conversion format is required for TO_NUMBER") 3695 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3696 3697 return self.func("TO_NUMBER", expression.this, fmt) 3698 3699 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3700 this = self.sql(expression, "this") 3701 kind = self.sql(expression, "kind") 3702 settings_sql = self.expressions(expression, key="settings", sep=" ") 3703 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3704 return f"{this}({kind}{args})" 3705 3706 def dictrange_sql(self, expression: exp.DictRange) -> str: 3707 this = self.sql(expression, "this") 3708 max = self.sql(expression, "max") 3709 min = self.sql(expression, "min") 3710 return f"{this}(MIN {min} MAX {max})" 3711 3712 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3713 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3714 3715 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3716 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3717 3718 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3719 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3720 expressions = self.expressions(expression, flat=True) 3721 expressions = f" {self.wrap(expressions)}" if expressions else "" 3722 buckets = self.sql(expression, "buckets") 3723 kind = self.sql(expression, "kind") 3724 buckets = f" BUCKETS {buckets}" if buckets else "" 3725 order = self.sql(expression, "order") 3726 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3727 3728 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3729 return "" 3730 3731 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3732 expressions = self.expressions(expression, key="expressions", flat=True) 3733 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3734 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3735 buckets = self.sql(expression, "buckets") 3736 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3737 3738 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3739 this = self.sql(expression, "this") 3740 having = self.sql(expression, "having") 3741 3742 if having: 3743 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3744 3745 return self.func("ANY_VALUE", this) 3746 3747 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3748 transform = self.func("TRANSFORM", *expression.expressions) 3749 row_format_before = self.sql(expression, "row_format_before") 3750 row_format_before = f" {row_format_before}" if row_format_before else "" 3751 record_writer = self.sql(expression, "record_writer") 3752 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3753 using = f" USING {self.sql(expression, 'command_script')}" 3754 schema = self.sql(expression, "schema") 3755 schema = f" AS {schema}" if schema else "" 3756 row_format_after = self.sql(expression, "row_format_after") 3757 row_format_after = f" {row_format_after}" if row_format_after else "" 3758 record_reader = self.sql(expression, "record_reader") 3759 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3760 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3761 3762 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3763 key_block_size = self.sql(expression, "key_block_size") 3764 if key_block_size: 3765 return f"KEY_BLOCK_SIZE = {key_block_size}" 3766 3767 using = self.sql(expression, "using") 3768 if using: 3769 return f"USING {using}" 3770 3771 parser = self.sql(expression, "parser") 3772 if parser: 3773 return f"WITH PARSER {parser}" 3774 3775 comment = self.sql(expression, "comment") 3776 if comment: 3777 return f"COMMENT {comment}" 3778 3779 visible = expression.args.get("visible") 3780 if visible is not None: 3781 return "VISIBLE" if visible else "INVISIBLE" 3782 3783 engine_attr = self.sql(expression, "engine_attr") 3784 if engine_attr: 3785 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3786 3787 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3788 if secondary_engine_attr: 3789 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3790 3791 self.unsupported("Unsupported index constraint option.") 3792 return "" 3793 3794 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3795 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3796 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3797 3798 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3799 kind = self.sql(expression, "kind") 3800 kind = f"{kind} INDEX" if kind else "INDEX" 3801 this = self.sql(expression, "this") 3802 this = f" {this}" if this else "" 3803 index_type = self.sql(expression, "index_type") 3804 index_type = f" USING {index_type}" if index_type else "" 3805 expressions = self.expressions(expression, flat=True) 3806 expressions = f" ({expressions})" if expressions else "" 3807 options = self.expressions(expression, key="options", sep=" ") 3808 options = f" {options}" if options else "" 3809 return f"{kind}{this}{index_type}{expressions}{options}" 3810 3811 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3812 if self.NVL2_SUPPORTED: 3813 return self.function_fallback_sql(expression) 3814 3815 case = exp.Case().when( 3816 expression.this.is_(exp.null()).not_(copy=False), 3817 expression.args["true"], 3818 copy=False, 3819 ) 3820 else_cond = expression.args.get("false") 3821 if else_cond: 3822 case.else_(else_cond, copy=False) 3823 3824 return self.sql(case) 3825 3826 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3827 this = self.sql(expression, "this") 3828 expr = self.sql(expression, "expression") 3829 iterator = self.sql(expression, "iterator") 3830 condition = self.sql(expression, "condition") 3831 condition = f" IF {condition}" if condition else "" 3832 return f"{this} FOR {expr} IN {iterator}{condition}" 3833 3834 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3835 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3836 3837 def opclass_sql(self, expression: exp.Opclass) -> str: 3838 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3839 3840 def predict_sql(self, expression: exp.Predict) -> str: 3841 model = self.sql(expression, "this") 3842 model = f"MODEL {model}" 3843 table = self.sql(expression, "expression") 3844 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3845 parameters = self.sql(expression, "params_struct") 3846 return self.func("PREDICT", model, table, parameters or None) 3847 3848 def forin_sql(self, expression: exp.ForIn) -> str: 3849 this = self.sql(expression, "this") 3850 expression_sql = self.sql(expression, "expression") 3851 return f"FOR {this} DO {expression_sql}" 3852 3853 def refresh_sql(self, expression: exp.Refresh) -> str: 3854 this = self.sql(expression, "this") 3855 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3856 return f"REFRESH {table}{this}" 3857 3858 def toarray_sql(self, expression: exp.ToArray) -> str: 3859 arg = expression.this 3860 if not arg.type: 3861 from sqlglot.optimizer.annotate_types import annotate_types 3862 3863 arg = annotate_types(arg) 3864 3865 if arg.is_type(exp.DataType.Type.ARRAY): 3866 return self.sql(arg) 3867 3868 cond_for_null = arg.is_(exp.null()) 3869 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 3870 3871 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 3872 this = expression.this 3873 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 3874 return self.sql(this) 3875 3876 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 3877 3878 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 3879 this = expression.this 3880 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 3881 return self.sql(this) 3882 3883 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP)) 3884 3885 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 3886 this = expression.this 3887 time_format = self.format_time(expression) 3888 3889 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 3890 return self.sql( 3891 exp.cast( 3892 exp.StrToTime(this=this, format=expression.args["format"]), 3893 exp.DataType.Type.DATE, 3894 ) 3895 ) 3896 3897 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 3898 return self.sql(this) 3899 3900 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 3901 3902 def unixdate_sql(self, expression: exp.UnixDate) -> str: 3903 return self.sql( 3904 exp.func( 3905 "DATEDIFF", 3906 expression.this, 3907 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 3908 "day", 3909 ) 3910 ) 3911 3912 def lastday_sql(self, expression: exp.LastDay) -> str: 3913 if self.LAST_DAY_SUPPORTS_DATE_PART: 3914 return self.function_fallback_sql(expression) 3915 3916 unit = expression.text("unit") 3917 if unit and unit != "MONTH": 3918 self.unsupported("Date parts are not supported in LAST_DAY.") 3919 3920 return self.func("LAST_DAY", expression.this) 3921 3922 def dateadd_sql(self, expression: exp.DateAdd) -> str: 3923 from sqlglot.dialects.dialect import unit_to_str 3924 3925 return self.func( 3926 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 3927 ) 3928 3929 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 3930 if self.CAN_IMPLEMENT_ARRAY_ANY: 3931 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 3932 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 3933 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 3934 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 3935 3936 from sqlglot.dialects import Dialect 3937 3938 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 3939 if self.dialect.__class__ != Dialect: 3940 self.unsupported("ARRAY_ANY is unsupported") 3941 3942 return self.function_fallback_sql(expression) 3943 3944 def struct_sql(self, expression: exp.Struct) -> str: 3945 expression.set( 3946 "expressions", 3947 [ 3948 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 3949 if isinstance(e, exp.PropertyEQ) 3950 else e 3951 for e in expression.expressions 3952 ], 3953 ) 3954 3955 return self.function_fallback_sql(expression) 3956 3957 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 3958 low = self.sql(expression, "this") 3959 high = self.sql(expression, "expression") 3960 3961 return f"{low} TO {high}" 3962 3963 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 3964 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 3965 tables = f" {self.expressions(expression)}" 3966 3967 exists = " IF EXISTS" if expression.args.get("exists") else "" 3968 3969 on_cluster = self.sql(expression, "cluster") 3970 on_cluster = f" {on_cluster}" if on_cluster else "" 3971 3972 identity = self.sql(expression, "identity") 3973 identity = f" {identity} IDENTITY" if identity else "" 3974 3975 option = self.sql(expression, "option") 3976 option = f" {option}" if option else "" 3977 3978 partition = self.sql(expression, "partition") 3979 partition = f" {partition}" if partition else "" 3980 3981 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 3982 3983 # This transpiles T-SQL's CONVERT function 3984 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 3985 def convert_sql(self, expression: exp.Convert) -> str: 3986 to = expression.this 3987 value = expression.expression 3988 style = expression.args.get("style") 3989 safe = expression.args.get("safe") 3990 strict = expression.args.get("strict") 3991 3992 if not to or not value: 3993 return "" 3994 3995 # Retrieve length of datatype and override to default if not specified 3996 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 3997 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 3998 3999 transformed: t.Optional[exp.Expression] = None 4000 cast = exp.Cast if strict else exp.TryCast 4001 4002 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4003 if isinstance(style, exp.Literal) and style.is_int: 4004 from sqlglot.dialects.tsql import TSQL 4005 4006 style_value = style.name 4007 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4008 if not converted_style: 4009 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4010 4011 fmt = exp.Literal.string(converted_style) 4012 4013 if to.this == exp.DataType.Type.DATE: 4014 transformed = exp.StrToDate(this=value, format=fmt) 4015 elif to.this == exp.DataType.Type.DATETIME: 4016 transformed = exp.StrToTime(this=value, format=fmt) 4017 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4018 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4019 elif to.this == exp.DataType.Type.TEXT: 4020 transformed = exp.TimeToStr(this=value, format=fmt) 4021 4022 if not transformed: 4023 transformed = cast(this=value, to=to, safe=safe) 4024 4025 return self.sql(transformed) 4026 4027 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4028 this = expression.this 4029 if isinstance(this, exp.JSONPathWildcard): 4030 this = self.json_path_part(this) 4031 return f".{this}" if this else "" 4032 4033 if exp.SAFE_IDENTIFIER_RE.match(this): 4034 return f".{this}" 4035 4036 this = self.json_path_part(this) 4037 return f"[{this}]" if self.JSON_PATH_BRACKETED_KEY_SUPPORTED else f".{this}" 4038 4039 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4040 this = self.json_path_part(expression.this) 4041 return f"[{this}]" if this else "" 4042 4043 def _simplify_unless_literal(self, expression: E) -> E: 4044 if not isinstance(expression, exp.Literal): 4045 from sqlglot.optimizer.simplify import simplify 4046 4047 expression = simplify(expression, dialect=self.dialect) 4048 4049 return expression 4050 4051 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4052 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4053 # The first modifier here will be the one closest to the AggFunc's arg 4054 mods = sorted( 4055 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4056 key=lambda x: 0 4057 if isinstance(x, exp.HavingMax) 4058 else (1 if isinstance(x, exp.Order) else 2), 4059 ) 4060 4061 if mods: 4062 mod = mods[0] 4063 this = expression.__class__(this=mod.this.copy()) 4064 this.meta["inline"] = True 4065 mod.this.replace(this) 4066 return self.sql(expression.this) 4067 4068 agg_func = expression.find(exp.AggFunc) 4069 4070 if agg_func: 4071 return self.sql(agg_func)[:-1] + f" {text})" 4072 4073 return f"{self.sql(expression, 'this')} {text}" 4074 4075 def _replace_line_breaks(self, string: str) -> str: 4076 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4077 if self.pretty: 4078 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4079 return string 4080 4081 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4082 option = self.sql(expression, "this") 4083 4084 if expression.expressions: 4085 upper = option.upper() 4086 4087 # Snowflake FILE_FORMAT options are separated by whitespace 4088 sep = " " if upper == "FILE_FORMAT" else ", " 4089 4090 # Databricks copy/format options do not set their list of values with EQ 4091 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4092 values = self.expressions(expression, flat=True, sep=sep) 4093 return f"{option}{op}({values})" 4094 4095 value = self.sql(expression, "expression") 4096 4097 if not value: 4098 return option 4099 4100 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4101 4102 return f"{option}{op}{value}" 4103 4104 def credentials_sql(self, expression: exp.Credentials) -> str: 4105 cred_expr = expression.args.get("credentials") 4106 if isinstance(cred_expr, exp.Literal): 4107 # Redshift case: CREDENTIALS <string> 4108 credentials = self.sql(expression, "credentials") 4109 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4110 else: 4111 # Snowflake case: CREDENTIALS = (...) 4112 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4113 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4114 4115 storage = self.sql(expression, "storage") 4116 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4117 4118 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4119 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4120 4121 iam_role = self.sql(expression, "iam_role") 4122 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4123 4124 region = self.sql(expression, "region") 4125 region = f" REGION {region}" if region else "" 4126 4127 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4128 4129 def copy_sql(self, expression: exp.Copy) -> str: 4130 this = self.sql(expression, "this") 4131 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4132 4133 credentials = self.sql(expression, "credentials") 4134 credentials = self.seg(credentials) if credentials else "" 4135 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4136 files = self.expressions(expression, key="files", flat=True) 4137 4138 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4139 params = self.expressions( 4140 expression, 4141 key="params", 4142 sep=sep, 4143 new_line=True, 4144 skip_last=True, 4145 skip_first=True, 4146 indent=self.COPY_PARAMS_ARE_WRAPPED, 4147 ) 4148 4149 if params: 4150 if self.COPY_PARAMS_ARE_WRAPPED: 4151 params = f" WITH ({params})" 4152 elif not self.pretty: 4153 params = f" {params}" 4154 4155 return f"COPY{this}{kind} {files}{credentials}{params}" 4156 4157 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4158 return "" 4159 4160 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4161 on_sql = "ON" if expression.args.get("on") else "OFF" 4162 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4163 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4164 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4165 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4166 4167 if filter_col or retention_period: 4168 on_sql = self.func("ON", filter_col, retention_period) 4169 4170 return f"DATA_DELETION={on_sql}" 4171 4172 def maskingpolicycolumnconstraint_sql( 4173 self, expression: exp.MaskingPolicyColumnConstraint 4174 ) -> str: 4175 this = self.sql(expression, "this") 4176 expressions = self.expressions(expression, flat=True) 4177 expressions = f" USING ({expressions})" if expressions else "" 4178 return f"MASKING POLICY {this}{expressions}" 4179 4180 def gapfill_sql(self, expression: exp.GapFill) -> str: 4181 this = self.sql(expression, "this") 4182 this = f"TABLE {this}" 4183 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4184 4185 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4186 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4187 4188 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4189 this = self.sql(expression, "this") 4190 expr = expression.expression 4191 4192 if isinstance(expr, exp.Func): 4193 # T-SQL's CLR functions are case sensitive 4194 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4195 else: 4196 expr = self.sql(expression, "expression") 4197 4198 return self.scope_resolution(expr, this) 4199 4200 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4201 if self.PARSE_JSON_NAME is None: 4202 return self.sql(expression.this) 4203 4204 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4205 4206 def rand_sql(self, expression: exp.Rand) -> str: 4207 lower = self.sql(expression, "lower") 4208 upper = self.sql(expression, "upper") 4209 4210 if lower and upper: 4211 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4212 return self.func("RAND", expression.this) 4213 4214 def changes_sql(self, expression: exp.Changes) -> str: 4215 information = self.sql(expression, "information") 4216 information = f"INFORMATION => {information}" 4217 at_before = self.sql(expression, "at_before") 4218 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4219 end = self.sql(expression, "end") 4220 end = f"{self.seg('')}{end}" if end else "" 4221 4222 return f"CHANGES ({information}){at_before}{end}" 4223 4224 def pad_sql(self, expression: exp.Pad) -> str: 4225 prefix = "L" if expression.args.get("is_left") else "R" 4226 4227 fill_pattern = self.sql(expression, "fill_pattern") or None 4228 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4229 fill_pattern = "' '" 4230 4231 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4232 4233 def summarize_sql(self, expression: exp.Summarize) -> str: 4234 table = " TABLE" if expression.args.get("table") else "" 4235 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4236 4237 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4238 generate_series = exp.GenerateSeries(**expression.args) 4239 4240 parent = expression.parent 4241 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4242 parent = parent.parent 4243 4244 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4245 return self.sql(exp.Unnest(expressions=[generate_series])) 4246 4247 if isinstance(parent, exp.Select): 4248 self.unsupported("GenerateSeries projection unnesting is not supported.") 4249 4250 return self.sql(generate_series) 4251 4252 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4253 exprs = expression.expressions 4254 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4255 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4256 else: 4257 rhs = self.expressions(expression) 4258 4259 return self.func(name, expression.this, rhs or None) 4260 4261 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4262 if self.SUPPORTS_CONVERT_TIMEZONE: 4263 return self.function_fallback_sql(expression) 4264 4265 source_tz = expression.args.get("source_tz") 4266 target_tz = expression.args.get("target_tz") 4267 timestamp = expression.args.get("timestamp") 4268 4269 if source_tz and timestamp: 4270 timestamp = exp.AtTimeZone( 4271 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4272 ) 4273 4274 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4275 4276 return self.sql(expr) 4277 4278 def json_sql(self, expression: exp.JSON) -> str: 4279 this = self.sql(expression, "this") 4280 this = f" {this}" if this else "" 4281 4282 _with = expression.args.get("with") 4283 4284 if _with is None: 4285 with_sql = "" 4286 elif not _with: 4287 with_sql = " WITHOUT" 4288 else: 4289 with_sql = " WITH" 4290 4291 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4292 4293 return f"JSON{this}{with_sql}{unique_sql}" 4294 4295 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4296 def _generate_on_options(arg: t.Any) -> str: 4297 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4298 4299 path = self.sql(expression, "path") 4300 returning = self.sql(expression, "returning") 4301 returning = f" RETURNING {returning}" if returning else "" 4302 4303 on_condition = self.sql(expression, "on_condition") 4304 on_condition = f" {on_condition}" if on_condition else "" 4305 4306 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4307 4308 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4309 else_ = "ELSE " if expression.args.get("else_") else "" 4310 condition = self.sql(expression, "expression") 4311 condition = f"WHEN {condition} THEN " if condition else else_ 4312 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4313 return f"{condition}{insert}" 4314 4315 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4316 kind = self.sql(expression, "kind") 4317 expressions = self.seg(self.expressions(expression, sep=" ")) 4318 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4319 return res 4320 4321 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4322 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4323 empty = expression.args.get("empty") 4324 empty = ( 4325 f"DEFAULT {empty} ON EMPTY" 4326 if isinstance(empty, exp.Expression) 4327 else self.sql(expression, "empty") 4328 ) 4329 4330 error = expression.args.get("error") 4331 error = ( 4332 f"DEFAULT {error} ON ERROR" 4333 if isinstance(error, exp.Expression) 4334 else self.sql(expression, "error") 4335 ) 4336 4337 if error and empty: 4338 error = ( 4339 f"{empty} {error}" 4340 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4341 else f"{error} {empty}" 4342 ) 4343 empty = "" 4344 4345 null = self.sql(expression, "null") 4346 4347 return f"{empty}{error}{null}" 4348 4349 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4350 this = self.sql(expression, "this") 4351 path = self.sql(expression, "path") 4352 4353 passing = self.expressions(expression, "passing") 4354 passing = f" PASSING {passing}" if passing else "" 4355 4356 on_condition = self.sql(expression, "on_condition") 4357 on_condition = f" {on_condition}" if on_condition else "" 4358 4359 path = f"{path}{passing}{on_condition}" 4360 4361 return self.func("JSON_EXISTS", this, path) 4362 4363 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4364 array_agg = self.function_fallback_sql(expression) 4365 4366 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4367 parent = expression.parent 4368 if isinstance(parent, exp.Filter): 4369 parent_cond = parent.expression.this 4370 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4371 else: 4372 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4373 this = expression.this 4374 this_sql = ( 4375 self.expressions(this) 4376 if isinstance(this, exp.Distinct) 4377 else self.sql(expression, "this") 4378 ) 4379 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4380 4381 return array_agg 4382 4383 def apply_sql(self, expression: exp.Apply) -> str: 4384 this = self.sql(expression, "this") 4385 expr = self.sql(expression, "expression") 4386 4387 return f"{this} APPLY({expr})" 4388 4389 def grant_sql(self, expression: exp.Grant) -> str: 4390 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4391 4392 kind = self.sql(expression, "kind") 4393 kind = f" {kind}" if kind else "" 4394 4395 securable = self.sql(expression, "securable") 4396 securable = f" {securable}" if securable else "" 4397 4398 principals = self.expressions(expression, key="principals", flat=True) 4399 4400 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4401 4402 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4403 4404 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4405 this = self.sql(expression, "this") 4406 columns = self.expressions(expression, flat=True) 4407 columns = f"({columns})" if columns else "" 4408 4409 return f"{this}{columns}" 4410 4411 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4412 this = self.sql(expression, "this") 4413 4414 kind = self.sql(expression, "kind") 4415 kind = f"{kind} " if kind else "" 4416 4417 return f"{kind}{this}" 4418 4419 def columns_sql(self, expression: exp.Columns): 4420 func = self.function_fallback_sql(expression) 4421 if expression.args.get("unpack"): 4422 func = f"*{func}" 4423 4424 return func 4425 4426 def overlay_sql(self, expression: exp.Overlay): 4427 this = self.sql(expression, "this") 4428 expr = self.sql(expression, "expression") 4429 from_sql = self.sql(expression, "from") 4430 for_sql = self.sql(expression, "for") 4431 for_sql = f" FOR {for_sql}" if for_sql else "" 4432 4433 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4434 4435 @unsupported_args("format") 4436 def todouble_sql(self, expression: exp.ToDouble) -> str: 4437 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4438 4439 def string_sql(self, expression: exp.String) -> str: 4440 this = expression.this 4441 zone = expression.args.get("zone") 4442 4443 if zone: 4444 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4445 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4446 # set for source_tz to transpile the time conversion before the STRING cast 4447 this = exp.ConvertTimezone( 4448 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4449 ) 4450 4451 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
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)
642 def __init__( 643 self, 644 pretty: t.Optional[bool] = None, 645 identify: str | bool = False, 646 normalize: bool = False, 647 pad: int = 2, 648 indent: int = 2, 649 normalize_functions: t.Optional[str | bool] = None, 650 unsupported_level: ErrorLevel = ErrorLevel.WARN, 651 max_unsupported: int = 3, 652 leading_comma: bool = False, 653 max_text_width: int = 80, 654 comments: bool = True, 655 dialect: DialectType = None, 656 ): 657 import sqlglot 658 from sqlglot.dialects import Dialect 659 660 self.pretty = pretty if pretty is not None else sqlglot.pretty 661 self.identify = identify 662 self.normalize = normalize 663 self.pad = pad 664 self._indent = indent 665 self.unsupported_level = unsupported_level 666 self.max_unsupported = max_unsupported 667 self.leading_comma = leading_comma 668 self.max_text_width = max_text_width 669 self.comments = comments 670 self.dialect = Dialect.get_or_raise(dialect) 671 672 # This is both a Dialect property and a Generator argument, so we prioritize the latter 673 self.normalize_functions = ( 674 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 675 ) 676 677 self.unsupported_messages: t.List[str] = [] 678 self._escaped_quote_end: str = ( 679 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 680 ) 681 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 682 683 self._next_name = name_sequence("_t") 684 685 self._identifier_start = self.dialect.IDENTIFIER_START 686 self._identifier_end = self.dialect.IDENTIFIER_END
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.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.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.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.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.TagColumnConstraint'>: <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.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.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'}
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.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.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.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.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES =
{<Type.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>}
688 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 689 """ 690 Generates the SQL string corresponding to the given syntax tree. 691 692 Args: 693 expression: The syntax tree. 694 copy: Whether to copy the expression. The generator performs mutations so 695 it is safer to copy. 696 697 Returns: 698 The SQL string corresponding to `expression`. 699 """ 700 if copy: 701 expression = expression.copy() 702 703 expression = self.preprocess(expression) 704 705 self.unsupported_messages = [] 706 sql = self.sql(expression).strip() 707 708 if self.pretty: 709 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 710 711 if self.unsupported_level == ErrorLevel.IGNORE: 712 return sql 713 714 if self.unsupported_level == ErrorLevel.WARN: 715 for msg in self.unsupported_messages: 716 logger.warning(msg) 717 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 718 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 719 720 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:
722 def preprocess(self, expression: exp.Expression) -> exp.Expression: 723 """Apply generic preprocessing transformations to a given expression.""" 724 expression = self._move_ctes_to_top_level(expression) 725 726 if self.ENSURE_BOOLS: 727 from sqlglot.transforms import ensure_bools 728 729 expression = ensure_bools(expression) 730 731 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:
760 def maybe_comment( 761 self, 762 sql: str, 763 expression: t.Optional[exp.Expression] = None, 764 comments: t.Optional[t.List[str]] = None, 765 separated: bool = False, 766 ) -> str: 767 comments = ( 768 ((expression and expression.comments) if comments is None else comments) # type: ignore 769 if self.comments 770 else None 771 ) 772 773 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 774 return sql 775 776 comments_sql = " ".join( 777 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 778 ) 779 780 if not comments_sql: 781 return sql 782 783 comments_sql = self._replace_line_breaks(comments_sql) 784 785 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 786 return ( 787 f"{self.sep()}{comments_sql}{sql}" 788 if not sql or sql[0].isspace() 789 else f"{comments_sql}{self.sep()}{sql}" 790 ) 791 792 return f"{sql} {comments_sql}"
794 def wrap(self, expression: exp.Expression | str) -> str: 795 this_sql = ( 796 self.sql(expression) 797 if isinstance(expression, exp.UNWRAPPED_QUERIES) 798 else self.sql(expression, "this") 799 ) 800 if not this_sql: 801 return "()" 802 803 this_sql = self.indent(this_sql, level=1, pad=0) 804 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:
820 def indent( 821 self, 822 sql: str, 823 level: int = 0, 824 pad: t.Optional[int] = None, 825 skip_first: bool = False, 826 skip_last: bool = False, 827 ) -> str: 828 if not self.pretty or not sql: 829 return sql 830 831 pad = self.pad if pad is None else pad 832 lines = sql.split("\n") 833 834 return "\n".join( 835 ( 836 line 837 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 838 else f"{' ' * (level * self._indent + pad)}{line}" 839 ) 840 for i, line in enumerate(lines) 841 )
def
sql( self, expression: Union[str, sqlglot.expressions.Expression, NoneType], key: Optional[str] = None, comment: bool = True) -> str:
843 def sql( 844 self, 845 expression: t.Optional[str | exp.Expression], 846 key: t.Optional[str] = None, 847 comment: bool = True, 848 ) -> str: 849 if not expression: 850 return "" 851 852 if isinstance(expression, str): 853 return expression 854 855 if key: 856 value = expression.args.get(key) 857 if value: 858 return self.sql(value) 859 return "" 860 861 transform = self.TRANSFORMS.get(expression.__class__) 862 863 if callable(transform): 864 sql = transform(self, expression) 865 elif isinstance(expression, exp.Expression): 866 exp_handler_name = f"{expression.key}_sql" 867 868 if hasattr(self, exp_handler_name): 869 sql = getattr(self, exp_handler_name)(expression) 870 elif isinstance(expression, exp.Func): 871 sql = self.function_fallback_sql(expression) 872 elif isinstance(expression, exp.Property): 873 sql = self.property_sql(expression) 874 else: 875 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 876 else: 877 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 878 879 return self.maybe_comment(sql, expression) if self.comments and comment else sql
886 def cache_sql(self, expression: exp.Cache) -> str: 887 lazy = " LAZY" if expression.args.get("lazy") else "" 888 table = self.sql(expression, "this") 889 options = expression.args.get("options") 890 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 891 sql = self.sql(expression, "expression") 892 sql = f" AS{self.sep()}{sql}" if sql else "" 893 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 894 return self.prepend_ctes(expression, sql)
896 def characterset_sql(self, expression: exp.CharacterSet) -> str: 897 if isinstance(expression.parent, exp.Cast): 898 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 899 default = "DEFAULT " if expression.args.get("default") else "" 900 return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
914 def column_sql(self, expression: exp.Column) -> str: 915 join_mark = " (+)" if expression.args.get("join_mark") else "" 916 917 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 918 join_mark = "" 919 self.unsupported("Outer join syntax using the (+) operator is not supported.") 920 921 return f"{self.column_parts(expression)}{join_mark}"
929 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 930 column = self.sql(expression, "this") 931 kind = self.sql(expression, "kind") 932 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 933 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 934 kind = f"{sep}{kind}" if kind else "" 935 constraints = f" {constraints}" if constraints else "" 936 position = self.sql(expression, "position") 937 position = f" {position}" if position else "" 938 939 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 940 kind = "" 941 942 return f"{exists}{column}{kind}{constraints}{position}"
def
computedcolumnconstraint_sql(self, expression: sqlglot.expressions.ComputedColumnConstraint) -> str:
949 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 950 this = self.sql(expression, "this") 951 if expression.args.get("not_null"): 952 persisted = " PERSISTED NOT NULL" 953 elif expression.args.get("persisted"): 954 persisted = " PERSISTED" 955 else: 956 persisted = "" 957 return f"AS {this}{persisted}"
def
compresscolumnconstraint_sql(self, expression: sqlglot.expressions.CompressColumnConstraint) -> str:
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str:
970 def generatedasidentitycolumnconstraint_sql( 971 self, expression: exp.GeneratedAsIdentityColumnConstraint 972 ) -> str: 973 this = "" 974 if expression.this is not None: 975 on_null = " ON NULL" if expression.args.get("on_null") else "" 976 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 977 978 start = expression.args.get("start") 979 start = f"START WITH {start}" if start else "" 980 increment = expression.args.get("increment") 981 increment = f" INCREMENT BY {increment}" if increment else "" 982 minvalue = expression.args.get("minvalue") 983 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 984 maxvalue = expression.args.get("maxvalue") 985 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 986 cycle = expression.args.get("cycle") 987 cycle_sql = "" 988 989 if cycle is not None: 990 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 991 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 992 993 sequence_opts = "" 994 if start or increment or cycle_sql: 995 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 996 sequence_opts = f" ({sequence_opts.strip()})" 997 998 expr = self.sql(expression, "expression") 999 expr = f"({expr})" if expr else "IDENTITY" 1000 1001 return f"GENERATED{this} AS {expr}{sequence_opts}"
def
generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsRowColumnConstraint) -> str:
1003 def generatedasrowcolumnconstraint_sql( 1004 self, expression: exp.GeneratedAsRowColumnConstraint 1005 ) -> str: 1006 start = "START" if expression.args.get("start") else "END" 1007 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1008 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:
1027 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1028 this = self.sql(expression, "this") 1029 this = f" {this}" if this else "" 1030 index_type = expression.args.get("index_type") 1031 index_type = f" USING {index_type}" if index_type else "" 1032 on_conflict = self.sql(expression, "on_conflict") 1033 on_conflict = f" {on_conflict}" if on_conflict else "" 1034 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1035 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"
1040 def create_sql(self, expression: exp.Create) -> str: 1041 kind = self.sql(expression, "kind") 1042 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1043 properties = expression.args.get("properties") 1044 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1045 1046 this = self.createable_sql(expression, properties_locs) 1047 1048 properties_sql = "" 1049 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1050 exp.Properties.Location.POST_WITH 1051 ): 1052 properties_sql = self.sql( 1053 exp.Properties( 1054 expressions=[ 1055 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1056 *properties_locs[exp.Properties.Location.POST_WITH], 1057 ] 1058 ) 1059 ) 1060 1061 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1062 properties_sql = self.sep() + properties_sql 1063 elif not self.pretty: 1064 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1065 properties_sql = f" {properties_sql}" 1066 1067 begin = " BEGIN" if expression.args.get("begin") else "" 1068 end = " END" if expression.args.get("end") else "" 1069 1070 expression_sql = self.sql(expression, "expression") 1071 if expression_sql: 1072 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1073 1074 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1075 postalias_props_sql = "" 1076 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1077 postalias_props_sql = self.properties( 1078 exp.Properties( 1079 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1080 ), 1081 wrapped=False, 1082 ) 1083 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1084 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1085 1086 postindex_props_sql = "" 1087 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1088 postindex_props_sql = self.properties( 1089 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1090 wrapped=False, 1091 prefix=" ", 1092 ) 1093 1094 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1095 indexes = f" {indexes}" if indexes else "" 1096 index_sql = indexes + postindex_props_sql 1097 1098 replace = " OR REPLACE" if expression.args.get("replace") else "" 1099 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1100 unique = " UNIQUE" if expression.args.get("unique") else "" 1101 1102 clustered = expression.args.get("clustered") 1103 if clustered is None: 1104 clustered_sql = "" 1105 elif clustered: 1106 clustered_sql = " CLUSTERED COLUMNSTORE" 1107 else: 1108 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1109 1110 postcreate_props_sql = "" 1111 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1112 postcreate_props_sql = self.properties( 1113 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1114 sep=" ", 1115 prefix=" ", 1116 wrapped=False, 1117 ) 1118 1119 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1120 1121 postexpression_props_sql = "" 1122 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1123 postexpression_props_sql = self.properties( 1124 exp.Properties( 1125 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1126 ), 1127 sep=" ", 1128 prefix=" ", 1129 wrapped=False, 1130 ) 1131 1132 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1133 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1134 no_schema_binding = ( 1135 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1136 ) 1137 1138 clone = self.sql(expression, "clone") 1139 clone = f" {clone}" if clone else "" 1140 1141 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1142 return self.prepend_ctes(expression, expression_sql)
1144 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1145 start = self.sql(expression, "start") 1146 start = f"START WITH {start}" if start else "" 1147 increment = self.sql(expression, "increment") 1148 increment = f" INCREMENT BY {increment}" if increment else "" 1149 minvalue = self.sql(expression, "minvalue") 1150 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1151 maxvalue = self.sql(expression, "maxvalue") 1152 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1153 owned = self.sql(expression, "owned") 1154 owned = f" OWNED BY {owned}" if owned else "" 1155 1156 cache = expression.args.get("cache") 1157 if cache is None: 1158 cache_str = "" 1159 elif cache is True: 1160 cache_str = " CACHE" 1161 else: 1162 cache_str = f" CACHE {cache}" 1163 1164 options = self.expressions(expression, key="options", flat=True, sep=" ") 1165 options = f" {options}" if options else "" 1166 1167 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1169 def clone_sql(self, expression: exp.Clone) -> str: 1170 this = self.sql(expression, "this") 1171 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1172 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1173 return f"{shallow}{keyword} {this}"
1175 def describe_sql(self, expression: exp.Describe) -> str: 1176 style = expression.args.get("style") 1177 style = f" {style}" if style else "" 1178 partition = self.sql(expression, "partition") 1179 partition = f" {partition}" if partition else "" 1180 return f"DESCRIBE{style} {self.sql(expression, 'this')}{partition}"
1202 def cte_sql(self, expression: exp.CTE) -> str: 1203 alias = expression.args.get("alias") 1204 if alias: 1205 alias.add_comments(expression.pop_comments()) 1206 1207 alias_sql = self.sql(expression, "alias") 1208 1209 materialized = expression.args.get("materialized") 1210 if materialized is False: 1211 materialized = "NOT MATERIALIZED " 1212 elif materialized: 1213 materialized = "MATERIALIZED " 1214 1215 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
1217 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1218 alias = self.sql(expression, "this") 1219 columns = self.expressions(expression, key="columns", flat=True) 1220 columns = f"({columns})" if columns else "" 1221 1222 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1223 columns = "" 1224 self.unsupported("Named columns are not supported in table alias.") 1225 1226 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1227 alias = self._next_name() 1228 1229 return f"{alias}{columns}"
1249 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1250 this = self.sql(expression, "this") 1251 escape = expression.args.get("escape") 1252 1253 if self.dialect.UNICODE_START: 1254 escape_substitute = r"\\\1" 1255 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1256 else: 1257 escape_substitute = r"\\u\1" 1258 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1259 1260 if escape: 1261 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1262 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1263 else: 1264 escape_pattern = ESCAPED_UNICODE_RE 1265 escape_sql = "" 1266 1267 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1268 this = escape_pattern.sub(escape_substitute, this) 1269 1270 return f"{left_quote}{this}{right_quote}{escape_sql}"
1282 def datatype_sql(self, expression: exp.DataType) -> str: 1283 nested = "" 1284 values = "" 1285 interior = self.expressions(expression, flat=True) 1286 1287 type_value = expression.this 1288 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1289 type_sql = self.sql(expression, "kind") 1290 else: 1291 type_sql = ( 1292 self.TYPE_MAPPING.get(type_value, type_value.value) 1293 if isinstance(type_value, exp.DataType.Type) 1294 else type_value 1295 ) 1296 1297 if interior: 1298 if expression.args.get("nested"): 1299 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1300 if expression.args.get("values") is not None: 1301 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1302 values = self.expressions(expression, key="values", flat=True) 1303 values = f"{delimiters[0]}{values}{delimiters[1]}" 1304 elif type_value == exp.DataType.Type.INTERVAL: 1305 nested = f" {interior}" 1306 else: 1307 nested = f"({interior})" 1308 1309 type_sql = f"{type_sql}{nested}{values}" 1310 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1311 exp.DataType.Type.TIMETZ, 1312 exp.DataType.Type.TIMESTAMPTZ, 1313 ): 1314 type_sql = f"{type_sql} WITH TIME ZONE" 1315 1316 return type_sql
1318 def directory_sql(self, expression: exp.Directory) -> str: 1319 local = "LOCAL " if expression.args.get("local") else "" 1320 row_format = self.sql(expression, "row_format") 1321 row_format = f" {row_format}" if row_format else "" 1322 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1324 def delete_sql(self, expression: exp.Delete) -> str: 1325 this = self.sql(expression, "this") 1326 this = f" FROM {this}" if this else "" 1327 using = self.sql(expression, "using") 1328 using = f" USING {using}" if using else "" 1329 cluster = self.sql(expression, "cluster") 1330 cluster = f" {cluster}" if cluster else "" 1331 where = self.sql(expression, "where") 1332 returning = self.sql(expression, "returning") 1333 limit = self.sql(expression, "limit") 1334 tables = self.expressions(expression, key="tables") 1335 tables = f" {tables}" if tables else "" 1336 if self.RETURNING_END: 1337 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1338 else: 1339 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1340 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
1342 def drop_sql(self, expression: exp.Drop) -> str: 1343 this = self.sql(expression, "this") 1344 expressions = self.expressions(expression, flat=True) 1345 expressions = f" ({expressions})" if expressions else "" 1346 kind = expression.args["kind"] 1347 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1348 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1349 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1350 on_cluster = self.sql(expression, "cluster") 1351 on_cluster = f" {on_cluster}" if on_cluster else "" 1352 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1353 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1354 cascade = " CASCADE" if expression.args.get("cascade") else "" 1355 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1356 purge = " PURGE" if expression.args.get("purge") else "" 1357 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
1359 def set_operation(self, expression: exp.SetOperation) -> str: 1360 op_type = type(expression) 1361 op_name = op_type.key.upper() 1362 1363 distinct = expression.args.get("distinct") 1364 if ( 1365 distinct is False 1366 and op_type in (exp.Except, exp.Intersect) 1367 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1368 ): 1369 self.unsupported(f"{op_name} ALL is not supported") 1370 1371 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1372 1373 if distinct is None: 1374 distinct = default_distinct 1375 if distinct is None: 1376 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1377 1378 if distinct is default_distinct: 1379 kind = "" 1380 else: 1381 kind = " DISTINCT" if distinct else " ALL" 1382 1383 by_name = " BY NAME" if expression.args.get("by_name") else "" 1384 return f"{op_name}{kind}{by_name}"
1386 def set_operations(self, expression: exp.SetOperation) -> str: 1387 if not self.SET_OP_MODIFIERS: 1388 limit = expression.args.get("limit") 1389 order = expression.args.get("order") 1390 1391 if limit or order: 1392 select = self._move_ctes_to_top_level( 1393 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1394 ) 1395 1396 if limit: 1397 select = select.limit(limit.pop(), copy=False) 1398 if order: 1399 select = select.order_by(order.pop(), copy=False) 1400 return self.sql(select) 1401 1402 sqls: t.List[str] = [] 1403 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1404 1405 while stack: 1406 node = stack.pop() 1407 1408 if isinstance(node, exp.SetOperation): 1409 stack.append(node.expression) 1410 stack.append( 1411 self.maybe_comment( 1412 self.set_operation(node), comments=node.comments, separated=True 1413 ) 1414 ) 1415 stack.append(node.this) 1416 else: 1417 sqls.append(self.sql(node)) 1418 1419 this = self.sep().join(sqls) 1420 this = self.query_modifiers(expression, this) 1421 return self.prepend_ctes(expression, this)
1423 def fetch_sql(self, expression: exp.Fetch) -> str: 1424 direction = expression.args.get("direction") 1425 direction = f" {direction}" if direction else "" 1426 count = self.sql(expression, "count") 1427 count = f" {count}" if count else "" 1428 if expression.args.get("percent"): 1429 count = f"{count} PERCENT" 1430 with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY" 1431 return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"
1433 def filter_sql(self, expression: exp.Filter) -> str: 1434 if self.AGGREGATE_FILTER_SUPPORTED: 1435 this = self.sql(expression, "this") 1436 where = self.sql(expression, "expression").strip() 1437 return f"{this} FILTER({where})" 1438 1439 agg = expression.this 1440 agg_arg = agg.this 1441 cond = expression.expression.this 1442 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1443 return self.sql(agg)
1452 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1453 using = self.sql(expression, "using") 1454 using = f" USING {using}" if using else "" 1455 columns = self.expressions(expression, key="columns", flat=True) 1456 columns = f"({columns})" if columns else "" 1457 partition_by = self.expressions(expression, key="partition_by", flat=True) 1458 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1459 where = self.sql(expression, "where") 1460 include = self.expressions(expression, key="include", flat=True) 1461 if include: 1462 include = f" INCLUDE ({include})" 1463 with_storage = self.expressions(expression, key="with_storage", flat=True) 1464 with_storage = f" WITH ({with_storage})" if with_storage else "" 1465 tablespace = self.sql(expression, "tablespace") 1466 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1467 on = self.sql(expression, "on") 1468 on = f" ON {on}" if on else "" 1469 1470 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
1472 def index_sql(self, expression: exp.Index) -> str: 1473 unique = "UNIQUE " if expression.args.get("unique") else "" 1474 primary = "PRIMARY " if expression.args.get("primary") else "" 1475 amp = "AMP " if expression.args.get("amp") else "" 1476 name = self.sql(expression, "this") 1477 name = f"{name} " if name else "" 1478 table = self.sql(expression, "table") 1479 table = f"{self.INDEX_ON} {table}" if table else "" 1480 1481 index = "INDEX " if not table else "" 1482 1483 params = self.sql(expression, "params") 1484 return f"{unique}{primary}{amp}{index}{name}{table}{params}"
1486 def identifier_sql(self, expression: exp.Identifier) -> str: 1487 text = expression.name 1488 lower = text.lower() 1489 text = lower if self.normalize and not expression.quoted else text 1490 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1491 if ( 1492 expression.quoted 1493 or self.dialect.can_identify(text, self.identify) 1494 or lower in self.RESERVED_KEYWORDS 1495 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1496 ): 1497 text = f"{self._identifier_start}{text}{self._identifier_end}" 1498 return text
1513 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1514 input_format = self.sql(expression, "input_format") 1515 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1516 output_format = self.sql(expression, "output_format") 1517 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1518 return self.sep().join((input_format, output_format))
1527 def properties_sql(self, expression: exp.Properties) -> str: 1528 root_properties = [] 1529 with_properties = [] 1530 1531 for p in expression.expressions: 1532 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1533 if p_loc == exp.Properties.Location.POST_WITH: 1534 with_properties.append(p) 1535 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1536 root_properties.append(p) 1537 1538 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1539 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1540 1541 if root_props and with_props and not self.pretty: 1542 with_props = " " + with_props 1543 1544 return root_props + with_props
def
properties( self, properties: sqlglot.expressions.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str:
1551 def properties( 1552 self, 1553 properties: exp.Properties, 1554 prefix: str = "", 1555 sep: str = ", ", 1556 suffix: str = "", 1557 wrapped: bool = True, 1558 ) -> str: 1559 if properties.expressions: 1560 expressions = self.expressions(properties, sep=sep, indent=False) 1561 if expressions: 1562 expressions = self.wrap(expressions) if wrapped else expressions 1563 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1564 return ""
1569 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1570 properties_locs = defaultdict(list) 1571 for p in properties.expressions: 1572 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1573 if p_loc != exp.Properties.Location.UNSUPPORTED: 1574 properties_locs[p_loc].append(p) 1575 else: 1576 self.unsupported(f"Unsupported property {p.key}") 1577 1578 return properties_locs
def
property_name( self, expression: sqlglot.expressions.Property, string_key: bool = False) -> str:
1585 def property_sql(self, expression: exp.Property) -> str: 1586 property_cls = expression.__class__ 1587 if property_cls == exp.Property: 1588 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1589 1590 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1591 if not property_name: 1592 self.unsupported(f"Unsupported property {expression.key}") 1593 1594 return f"{property_name}={self.sql(expression, 'this')}"
1596 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1597 if self.SUPPORTS_CREATE_TABLE_LIKE: 1598 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1599 options = f" {options}" if options else "" 1600 1601 like = f"LIKE {self.sql(expression, 'this')}{options}" 1602 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1603 like = f"({like})" 1604 1605 return like 1606 1607 if expression.expressions: 1608 self.unsupported("Transpilation of LIKE property options is unsupported") 1609 1610 select = exp.select("*").from_(expression.this).limit(0) 1611 return f"AS {self.sql(select)}"
1618 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1619 no = "NO " if expression.args.get("no") else "" 1620 local = expression.args.get("local") 1621 local = f"{local} " if local else "" 1622 dual = "DUAL " if expression.args.get("dual") else "" 1623 before = "BEFORE " if expression.args.get("before") else "" 1624 after = "AFTER " if expression.args.get("after") else "" 1625 return f"{no}{local}{dual}{before}{after}JOURNAL"
def
mergeblockratioproperty_sql(self, expression: sqlglot.expressions.MergeBlockRatioProperty) -> str:
1641 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1642 if expression.args.get("no"): 1643 return "NO MERGEBLOCKRATIO" 1644 if expression.args.get("default"): 1645 return "DEFAULT MERGEBLOCKRATIO" 1646 1647 percent = " PERCENT" if expression.args.get("percent") else "" 1648 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
1650 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1651 default = expression.args.get("default") 1652 minimum = expression.args.get("minimum") 1653 maximum = expression.args.get("maximum") 1654 if default or minimum or maximum: 1655 if default: 1656 prop = "DEFAULT" 1657 elif minimum: 1658 prop = "MINIMUM" 1659 else: 1660 prop = "MAXIMUM" 1661 return f"{prop} DATABLOCKSIZE" 1662 units = expression.args.get("units") 1663 units = f" {units}" if units else "" 1664 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
def
blockcompressionproperty_sql(self, expression: sqlglot.expressions.BlockCompressionProperty) -> str:
1666 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1667 autotemp = expression.args.get("autotemp") 1668 always = expression.args.get("always") 1669 default = expression.args.get("default") 1670 manual = expression.args.get("manual") 1671 never = expression.args.get("never") 1672 1673 if autotemp is not None: 1674 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1675 elif always: 1676 prop = "ALWAYS" 1677 elif default: 1678 prop = "DEFAULT" 1679 elif manual: 1680 prop = "MANUAL" 1681 elif never: 1682 prop = "NEVER" 1683 return f"BLOCKCOMPRESSION={prop}"
def
isolatedloadingproperty_sql(self, expression: sqlglot.expressions.IsolatedLoadingProperty) -> str:
1685 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1686 no = expression.args.get("no") 1687 no = " NO" if no else "" 1688 concurrent = expression.args.get("concurrent") 1689 concurrent = " CONCURRENT" if concurrent else "" 1690 target = self.sql(expression, "target") 1691 target = f" {target}" if target else "" 1692 return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
1694 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1695 if isinstance(expression.this, list): 1696 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1697 if expression.this: 1698 modulus = self.sql(expression, "this") 1699 remainder = self.sql(expression, "expression") 1700 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1701 1702 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1703 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1704 return f"FROM ({from_expressions}) TO ({to_expressions})"
1706 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1707 this = self.sql(expression, "this") 1708 1709 for_values_or_default = expression.expression 1710 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1711 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1712 else: 1713 for_values_or_default = " DEFAULT" 1714 1715 return f"PARTITION OF {this}{for_values_or_default}"
1717 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1718 kind = expression.args.get("kind") 1719 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1720 for_or_in = expression.args.get("for_or_in") 1721 for_or_in = f" {for_or_in}" if for_or_in else "" 1722 lock_type = expression.args.get("lock_type") 1723 override = " OVERRIDE" if expression.args.get("override") else "" 1724 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
1726 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1727 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1728 statistics = expression.args.get("statistics") 1729 statistics_sql = "" 1730 if statistics is not None: 1731 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1732 return f"{data_sql}{statistics_sql}"
def
withsystemversioningproperty_sql( self, expression: sqlglot.expressions.WithSystemVersioningProperty) -> str:
1734 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1735 this = self.sql(expression, "this") 1736 this = f"HISTORY_TABLE={this}" if this else "" 1737 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1738 data_consistency = ( 1739 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1740 ) 1741 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1742 retention_period = ( 1743 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1744 ) 1745 1746 if this: 1747 on_sql = self.func("ON", this, data_consistency, retention_period) 1748 else: 1749 on_sql = "ON" if expression.args.get("on") else "OFF" 1750 1751 sql = f"SYSTEM_VERSIONING={on_sql}" 1752 1753 return f"WITH({sql})" if expression.args.get("with") else sql
1755 def insert_sql(self, expression: exp.Insert) -> str: 1756 hint = self.sql(expression, "hint") 1757 overwrite = expression.args.get("overwrite") 1758 1759 if isinstance(expression.this, exp.Directory): 1760 this = " OVERWRITE" if overwrite else " INTO" 1761 else: 1762 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1763 1764 stored = self.sql(expression, "stored") 1765 stored = f" {stored}" if stored else "" 1766 alternative = expression.args.get("alternative") 1767 alternative = f" OR {alternative}" if alternative else "" 1768 ignore = " IGNORE" if expression.args.get("ignore") else "" 1769 is_function = expression.args.get("is_function") 1770 if is_function: 1771 this = f"{this} FUNCTION" 1772 this = f"{this} {self.sql(expression, 'this')}" 1773 1774 exists = " IF EXISTS" if expression.args.get("exists") else "" 1775 where = self.sql(expression, "where") 1776 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1777 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1778 on_conflict = self.sql(expression, "conflict") 1779 on_conflict = f" {on_conflict}" if on_conflict else "" 1780 by_name = " BY NAME" if expression.args.get("by_name") else "" 1781 returning = self.sql(expression, "returning") 1782 1783 if self.RETURNING_END: 1784 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1785 else: 1786 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1787 1788 partition_by = self.sql(expression, "partition") 1789 partition_by = f" {partition_by}" if partition_by else "" 1790 settings = self.sql(expression, "settings") 1791 settings = f" {settings}" if settings else "" 1792 1793 source = self.sql(expression, "source") 1794 source = f"TABLE {source}" if source else "" 1795 1796 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1797 return self.prepend_ctes(expression, sql)
1815 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1816 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1817 1818 constraint = self.sql(expression, "constraint") 1819 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1820 1821 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1822 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1823 action = self.sql(expression, "action") 1824 1825 expressions = self.expressions(expression, flat=True) 1826 if expressions: 1827 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1828 expressions = f" {set_keyword}{expressions}" 1829 1830 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"
def
rowformatdelimitedproperty_sql(self, expression: sqlglot.expressions.RowFormatDelimitedProperty) -> str:
1835 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1836 fields = self.sql(expression, "fields") 1837 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1838 escaped = self.sql(expression, "escaped") 1839 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1840 items = self.sql(expression, "collection_items") 1841 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1842 keys = self.sql(expression, "map_keys") 1843 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1844 lines = self.sql(expression, "lines") 1845 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1846 null = self.sql(expression, "null") 1847 null = f" NULL DEFINED AS {null}" if null else "" 1848 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
1876 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1877 table = self.table_parts(expression) 1878 only = "ONLY " if expression.args.get("only") else "" 1879 partition = self.sql(expression, "partition") 1880 partition = f" {partition}" if partition else "" 1881 version = self.sql(expression, "version") 1882 version = f" {version}" if version else "" 1883 alias = self.sql(expression, "alias") 1884 alias = f"{sep}{alias}" if alias else "" 1885 1886 sample = self.sql(expression, "sample") 1887 if self.dialect.ALIAS_POST_TABLESAMPLE: 1888 sample_pre_alias = sample 1889 sample_post_alias = "" 1890 else: 1891 sample_pre_alias = "" 1892 sample_post_alias = sample 1893 1894 hints = self.expressions(expression, key="hints", sep=" ") 1895 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1896 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1897 joins = self.indent( 1898 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1899 ) 1900 laterals = self.expressions(expression, key="laterals", sep="") 1901 1902 file_format = self.sql(expression, "format") 1903 if file_format: 1904 pattern = self.sql(expression, "pattern") 1905 pattern = f", PATTERN => {pattern}" if pattern else "" 1906 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1907 1908 ordinality = expression.args.get("ordinality") or "" 1909 if ordinality: 1910 ordinality = f" WITH ORDINALITY{alias}" 1911 alias = "" 1912 1913 when = self.sql(expression, "when") 1914 if when: 1915 table = f"{table} {when}" 1916 1917 changes = self.sql(expression, "changes") 1918 changes = f" {changes}" if changes else "" 1919 1920 rows_from = self.expressions(expression, key="rows_from") 1921 if rows_from: 1922 table = f"ROWS FROM {self.wrap(rows_from)}" 1923 1924 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:
1926 def tablesample_sql( 1927 self, 1928 expression: exp.TableSample, 1929 tablesample_keyword: t.Optional[str] = None, 1930 ) -> str: 1931 method = self.sql(expression, "method") 1932 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 1933 numerator = self.sql(expression, "bucket_numerator") 1934 denominator = self.sql(expression, "bucket_denominator") 1935 field = self.sql(expression, "bucket_field") 1936 field = f" ON {field}" if field else "" 1937 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 1938 seed = self.sql(expression, "seed") 1939 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 1940 1941 size = self.sql(expression, "size") 1942 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 1943 size = f"{size} ROWS" 1944 1945 percent = self.sql(expression, "percent") 1946 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 1947 percent = f"{percent} PERCENT" 1948 1949 expr = f"{bucket}{percent}{size}" 1950 if self.TABLESAMPLE_REQUIRES_PARENS: 1951 expr = f"({expr})" 1952 1953 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
1955 def pivot_sql(self, expression: exp.Pivot) -> str: 1956 expressions = self.expressions(expression, flat=True) 1957 1958 if expression.this: 1959 this = self.sql(expression, "this") 1960 if not expressions: 1961 return f"UNPIVOT {this}" 1962 1963 on = f"{self.seg('ON')} {expressions}" 1964 using = self.expressions(expression, key="using", flat=True) 1965 using = f"{self.seg('USING')} {using}" if using else "" 1966 group = self.sql(expression, "group") 1967 return f"PIVOT {this}{on}{using}{group}" 1968 1969 alias = self.sql(expression, "alias") 1970 alias = f" AS {alias}" if alias else "" 1971 direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT") 1972 1973 field = self.sql(expression, "field") 1974 1975 include_nulls = expression.args.get("include_nulls") 1976 if include_nulls is not None: 1977 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 1978 else: 1979 nulls = "" 1980 1981 default_on_null = self.sql(expression, "default_on_null") 1982 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 1983 return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}"
1994 def update_sql(self, expression: exp.Update) -> str: 1995 this = self.sql(expression, "this") 1996 set_sql = self.expressions(expression, flat=True) 1997 from_sql = self.sql(expression, "from") 1998 where_sql = self.sql(expression, "where") 1999 returning = self.sql(expression, "returning") 2000 order = self.sql(expression, "order") 2001 limit = self.sql(expression, "limit") 2002 if self.RETURNING_END: 2003 expression_sql = f"{from_sql}{where_sql}{returning}" 2004 else: 2005 expression_sql = f"{returning}{from_sql}{where_sql}" 2006 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2007 return self.prepend_ctes(expression, sql)
2009 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2010 values_as_table = values_as_table and self.VALUES_AS_TABLE 2011 2012 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2013 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2014 args = self.expressions(expression) 2015 alias = self.sql(expression, "alias") 2016 values = f"VALUES{self.seg('')}{args}" 2017 values = ( 2018 f"({values})" 2019 if self.WRAP_DERIVED_VALUES 2020 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2021 else values 2022 ) 2023 return f"{values} AS {alias}" if alias else values 2024 2025 # Converts `VALUES...` expression into a series of select unions. 2026 alias_node = expression.args.get("alias") 2027 column_names = alias_node and alias_node.columns 2028 2029 selects: t.List[exp.Query] = [] 2030 2031 for i, tup in enumerate(expression.expressions): 2032 row = tup.expressions 2033 2034 if i == 0 and column_names: 2035 row = [ 2036 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2037 ] 2038 2039 selects.append(exp.Select(expressions=row)) 2040 2041 if self.pretty: 2042 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2043 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2044 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2045 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2046 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2047 2048 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2049 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2050 return f"({unions}){alias}"
2055 @unsupported_args("expressions") 2056 def into_sql(self, expression: exp.Into) -> str: 2057 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2058 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2059 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2076 def group_sql(self, expression: exp.Group) -> str: 2077 group_by_all = expression.args.get("all") 2078 if group_by_all is True: 2079 modifier = " ALL" 2080 elif group_by_all is False: 2081 modifier = " DISTINCT" 2082 else: 2083 modifier = "" 2084 2085 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2086 2087 grouping_sets = self.expressions(expression, key="grouping_sets") 2088 cube = self.expressions(expression, key="cube") 2089 rollup = self.expressions(expression, key="rollup") 2090 2091 groupings = csv( 2092 self.seg(grouping_sets) if grouping_sets else "", 2093 self.seg(cube) if cube else "", 2094 self.seg(rollup) if rollup else "", 2095 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2096 sep=self.GROUPINGS_SEP, 2097 ) 2098 2099 if ( 2100 expression.expressions 2101 and groupings 2102 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2103 ): 2104 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2105 2106 return f"{group_by}{groupings}"
2112 def connect_sql(self, expression: exp.Connect) -> str: 2113 start = self.sql(expression, "start") 2114 start = self.seg(f"START WITH {start}") if start else "" 2115 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2116 connect = self.sql(expression, "connect") 2117 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2118 return start + connect
2123 def join_sql(self, expression: exp.Join) -> str: 2124 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2125 side = None 2126 else: 2127 side = expression.side 2128 2129 op_sql = " ".join( 2130 op 2131 for op in ( 2132 expression.method, 2133 "GLOBAL" if expression.args.get("global") else None, 2134 side, 2135 expression.kind, 2136 expression.hint if self.JOIN_HINTS else None, 2137 ) 2138 if op 2139 ) 2140 match_cond = self.sql(expression, "match_condition") 2141 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2142 on_sql = self.sql(expression, "on") 2143 using = expression.args.get("using") 2144 2145 if not on_sql and using: 2146 on_sql = csv(*(self.sql(column) for column in using)) 2147 2148 this = expression.this 2149 this_sql = self.sql(this) 2150 2151 exprs = self.expressions(expression) 2152 if exprs: 2153 this_sql = f"{this_sql},{self.seg(exprs)}" 2154 2155 if on_sql: 2156 on_sql = self.indent(on_sql, skip_first=True) 2157 space = self.seg(" " * self.pad) if self.pretty else " " 2158 if using: 2159 on_sql = f"{space}USING ({on_sql})" 2160 else: 2161 on_sql = f"{space}ON {on_sql}" 2162 elif not op_sql: 2163 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2164 return f" {this_sql}" 2165 2166 return f", {this_sql}" 2167 2168 if op_sql != "STRAIGHT_JOIN": 2169 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2170 2171 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
2178 def lateral_op(self, expression: exp.Lateral) -> str: 2179 cross_apply = expression.args.get("cross_apply") 2180 2181 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2182 if cross_apply is True: 2183 op = "INNER JOIN " 2184 elif cross_apply is False: 2185 op = "LEFT JOIN " 2186 else: 2187 op = "" 2188 2189 return f"{op}LATERAL"
2191 def lateral_sql(self, expression: exp.Lateral) -> str: 2192 this = self.sql(expression, "this") 2193 2194 if expression.args.get("view"): 2195 alias = expression.args["alias"] 2196 columns = self.expressions(alias, key="columns", flat=True) 2197 table = f" {alias.name}" if alias.name else "" 2198 columns = f" AS {columns}" if columns else "" 2199 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2200 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2201 2202 alias = self.sql(expression, "alias") 2203 alias = f" AS {alias}" if alias else "" 2204 return f"{self.lateral_op(expression)} {this}{alias}"
2206 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2207 this = self.sql(expression, "this") 2208 2209 args = [ 2210 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2211 for e in (expression.args.get(k) for k in ("offset", "expression")) 2212 if e 2213 ] 2214 2215 args_sql = ", ".join(self.sql(e) for e in args) 2216 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2217 expressions = self.expressions(expression, flat=True) 2218 expressions = f" BY {expressions}" if expressions else "" 2219 2220 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"
2222 def offset_sql(self, expression: exp.Offset) -> str: 2223 this = self.sql(expression, "this") 2224 value = expression.expression 2225 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2226 expressions = self.expressions(expression, flat=True) 2227 expressions = f" BY {expressions}" if expressions else "" 2228 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
2230 def setitem_sql(self, expression: exp.SetItem) -> str: 2231 kind = self.sql(expression, "kind") 2232 kind = f"{kind} " if kind else "" 2233 this = self.sql(expression, "this") 2234 expressions = self.expressions(expression) 2235 collate = self.sql(expression, "collate") 2236 collate = f" COLLATE {collate}" if collate else "" 2237 global_ = "GLOBAL " if expression.args.get("global") else "" 2238 return f"{global_}{kind}{this}{expressions}{collate}"
2240 def set_sql(self, expression: exp.Set) -> str: 2241 expressions = ( 2242 f" {self.expressions(expression, flat=True)}" if expression.expressions else "" 2243 ) 2244 tag = " TAG" if expression.args.get("tag") else "" 2245 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
2250 def lock_sql(self, expression: exp.Lock) -> str: 2251 if not self.LOCKING_READS_SUPPORTED: 2252 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2253 return "" 2254 2255 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2256 expressions = self.expressions(expression, flat=True) 2257 expressions = f" OF {expressions}" if expressions else "" 2258 wait = expression.args.get("wait") 2259 2260 if wait is not None: 2261 if isinstance(wait, exp.Literal): 2262 wait = f" WAIT {self.sql(wait)}" 2263 else: 2264 wait = " NOWAIT" if wait else " SKIP LOCKED" 2265 2266 return f"{lock_type}{expressions}{wait or ''}"
def
escape_str(self, text: str, escape_backslash: bool = True) -> str:
2274 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2275 if self.dialect.ESCAPED_SEQUENCES: 2276 to_escaped = self.dialect.ESCAPED_SEQUENCES 2277 text = "".join( 2278 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2279 ) 2280 2281 return self._replace_line_breaks(text).replace( 2282 self.dialect.QUOTE_END, self._escaped_quote_end 2283 )
2285 def loaddata_sql(self, expression: exp.LoadData) -> str: 2286 local = " LOCAL" if expression.args.get("local") else "" 2287 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2288 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2289 this = f" INTO TABLE {self.sql(expression, 'this')}" 2290 partition = self.sql(expression, "partition") 2291 partition = f" {partition}" if partition else "" 2292 input_format = self.sql(expression, "input_format") 2293 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2294 serde = self.sql(expression, "serde") 2295 serde = f" SERDE {serde}" if serde else "" 2296 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
2304 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2305 this = self.sql(expression, "this") 2306 this = f"{this} " if this else this 2307 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2308 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore
2310 def withfill_sql(self, expression: exp.WithFill) -> str: 2311 from_sql = self.sql(expression, "from") 2312 from_sql = f" FROM {from_sql}" if from_sql else "" 2313 to_sql = self.sql(expression, "to") 2314 to_sql = f" TO {to_sql}" if to_sql else "" 2315 step_sql = self.sql(expression, "step") 2316 step_sql = f" STEP {step_sql}" if step_sql else "" 2317 interpolated_values = [ 2318 f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}" 2319 for named_expression in expression.args.get("interpolate") or [] 2320 ] 2321 interpolate = ( 2322 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2323 ) 2324 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
2335 def ordered_sql(self, expression: exp.Ordered) -> str: 2336 desc = expression.args.get("desc") 2337 asc = not desc 2338 2339 nulls_first = expression.args.get("nulls_first") 2340 nulls_last = not nulls_first 2341 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2342 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2343 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2344 2345 this = self.sql(expression, "this") 2346 2347 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2348 nulls_sort_change = "" 2349 if nulls_first and ( 2350 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2351 ): 2352 nulls_sort_change = " NULLS FIRST" 2353 elif ( 2354 nulls_last 2355 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2356 and not nulls_are_last 2357 ): 2358 nulls_sort_change = " NULLS LAST" 2359 2360 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2361 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2362 window = expression.find_ancestor(exp.Window, exp.Select) 2363 if isinstance(window, exp.Window) and window.args.get("spec"): 2364 self.unsupported( 2365 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2366 ) 2367 nulls_sort_change = "" 2368 elif ( 2369 self.NULL_ORDERING_SUPPORTED is False 2370 and (isinstance(expression.find_ancestor(exp.AggFunc, exp.Select), exp.AggFunc)) 2371 and ( 2372 (asc and nulls_sort_change == " NULLS LAST") 2373 or (desc and nulls_sort_change == " NULLS FIRST") 2374 ) 2375 ): 2376 self.unsupported( 2377 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2378 ) 2379 nulls_sort_change = "" 2380 elif self.NULL_ORDERING_SUPPORTED is None: 2381 if expression.this.is_int: 2382 self.unsupported( 2383 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2384 ) 2385 elif not isinstance(expression.this, exp.Rand): 2386 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2387 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2388 nulls_sort_change = "" 2389 2390 with_fill = self.sql(expression, "with_fill") 2391 with_fill = f" {with_fill}" if with_fill else "" 2392 2393 return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
2403 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2404 partition = self.partition_by_sql(expression) 2405 order = self.sql(expression, "order") 2406 measures = self.expressions(expression, key="measures") 2407 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2408 rows = self.sql(expression, "rows") 2409 rows = self.seg(rows) if rows else "" 2410 after = self.sql(expression, "after") 2411 after = self.seg(after) if after else "" 2412 pattern = self.sql(expression, "pattern") 2413 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2414 definition_sqls = [ 2415 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2416 for definition in expression.args.get("define", []) 2417 ] 2418 definitions = self.expressions(sqls=definition_sqls) 2419 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2420 body = "".join( 2421 ( 2422 partition, 2423 order, 2424 measures, 2425 rows, 2426 after, 2427 pattern, 2428 define, 2429 ) 2430 ) 2431 alias = self.sql(expression, "alias") 2432 alias = f" {alias}" if alias else "" 2433 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
2435 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2436 limit = expression.args.get("limit") 2437 2438 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2439 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2440 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2441 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2442 2443 return csv( 2444 *sqls, 2445 *[self.sql(join) for join in expression.args.get("joins") or []], 2446 self.sql(expression, "connect"), 2447 self.sql(expression, "match"), 2448 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2449 self.sql(expression, "prewhere"), 2450 self.sql(expression, "where"), 2451 self.sql(expression, "group"), 2452 self.sql(expression, "having"), 2453 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2454 self.sql(expression, "order"), 2455 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2456 *self.after_limit_modifiers(expression), 2457 self.options_modifier(expression), 2458 sep="", 2459 )
def
offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]:
2468 def offset_limit_modifiers( 2469 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2470 ) -> t.List[str]: 2471 return [ 2472 self.sql(expression, "offset") if fetch else self.sql(limit), 2473 self.sql(limit) if fetch else self.sql(expression, "offset"), 2474 ]
2481 def select_sql(self, expression: exp.Select) -> str: 2482 into = expression.args.get("into") 2483 if not self.SUPPORTS_SELECT_INTO and into: 2484 into.pop() 2485 2486 hint = self.sql(expression, "hint") 2487 distinct = self.sql(expression, "distinct") 2488 distinct = f" {distinct}" if distinct else "" 2489 kind = self.sql(expression, "kind") 2490 2491 limit = expression.args.get("limit") 2492 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2493 top = self.limit_sql(limit, top=True) 2494 limit.pop() 2495 else: 2496 top = "" 2497 2498 expressions = self.expressions(expression) 2499 2500 if kind: 2501 if kind in self.SELECT_KINDS: 2502 kind = f" AS {kind}" 2503 else: 2504 if kind == "STRUCT": 2505 expressions = self.expressions( 2506 sqls=[ 2507 self.sql( 2508 exp.Struct( 2509 expressions=[ 2510 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2511 if isinstance(e, exp.Alias) 2512 else e 2513 for e in expression.expressions 2514 ] 2515 ) 2516 ) 2517 ] 2518 ) 2519 kind = "" 2520 2521 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2522 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2523 2524 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2525 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2526 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2527 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2528 sql = self.query_modifiers( 2529 expression, 2530 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2531 self.sql(expression, "into", comment=False), 2532 self.sql(expression, "from", comment=False), 2533 ) 2534 2535 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2536 if expression.args.get("with"): 2537 sql = self.maybe_comment(sql, expression) 2538 expression.pop_comments() 2539 2540 sql = self.prepend_ctes(expression, sql) 2541 2542 if not self.SUPPORTS_SELECT_INTO and into: 2543 if into.args.get("temporary"): 2544 table_kind = " TEMPORARY" 2545 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2546 table_kind = " UNLOGGED" 2547 else: 2548 table_kind = "" 2549 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2550 2551 return sql
2563 def star_sql(self, expression: exp.Star) -> str: 2564 except_ = self.expressions(expression, key="except", flat=True) 2565 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2566 replace = self.expressions(expression, key="replace", flat=True) 2567 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2568 rename = self.expressions(expression, key="rename", flat=True) 2569 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2570 return f"*{except_}{replace}{rename}"
2586 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2587 alias = self.sql(expression, "alias") 2588 alias = f"{sep}{alias}" if alias else "" 2589 sample = self.sql(expression, "sample") 2590 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2591 alias = f"{sample}{alias}" 2592 2593 # Set to None so it's not generated again by self.query_modifiers() 2594 expression.set("sample", None) 2595 2596 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2597 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2598 return self.prepend_ctes(expression, sql)
2604 def unnest_sql(self, expression: exp.Unnest) -> str: 2605 args = self.expressions(expression, flat=True) 2606 2607 alias = expression.args.get("alias") 2608 offset = expression.args.get("offset") 2609 2610 if self.UNNEST_WITH_ORDINALITY: 2611 if alias and isinstance(offset, exp.Expression): 2612 alias.append("columns", offset) 2613 2614 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2615 columns = alias.columns 2616 alias = self.sql(columns[0]) if columns else "" 2617 else: 2618 alias = self.sql(alias) 2619 2620 alias = f" AS {alias}" if alias else alias 2621 if self.UNNEST_WITH_ORDINALITY: 2622 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2623 else: 2624 if isinstance(offset, exp.Expression): 2625 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2626 elif offset: 2627 suffix = f"{alias} WITH OFFSET" 2628 else: 2629 suffix = alias 2630 2631 return f"UNNEST({args}){suffix}"
2640 def window_sql(self, expression: exp.Window) -> str: 2641 this = self.sql(expression, "this") 2642 partition = self.partition_by_sql(expression) 2643 order = expression.args.get("order") 2644 order = self.order_sql(order, flat=True) if order else "" 2645 spec = self.sql(expression, "spec") 2646 alias = self.sql(expression, "alias") 2647 over = self.sql(expression, "over") or "OVER" 2648 2649 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2650 2651 first = expression.args.get("first") 2652 if first is None: 2653 first = "" 2654 else: 2655 first = "FIRST" if first else "LAST" 2656 2657 if not partition and not order and not spec and alias: 2658 return f"{this} {alias}" 2659 2660 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2661 return f"{this} ({args})"
def
partition_by_sql( self, expression: sqlglot.expressions.Window | sqlglot.expressions.MatchRecognize) -> str:
2667 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2668 kind = self.sql(expression, "kind") 2669 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2670 end = ( 2671 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2672 or "CURRENT ROW" 2673 ) 2674 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]:
2687 def bracket_offset_expressions( 2688 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2689 ) -> t.List[exp.Expression]: 2690 return apply_index_offset( 2691 expression.this, 2692 expression.expressions, 2693 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2694 )
2704 def any_sql(self, expression: exp.Any) -> str: 2705 this = self.sql(expression, "this") 2706 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2707 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2708 this = self.wrap(this) 2709 return f"ANY{this}" 2710 return f"ANY {this}"
2715 def case_sql(self, expression: exp.Case) -> str: 2716 this = self.sql(expression, "this") 2717 statements = [f"CASE {this}" if this else "CASE"] 2718 2719 for e in expression.args["ifs"]: 2720 statements.append(f"WHEN {self.sql(e, 'this')}") 2721 statements.append(f"THEN {self.sql(e, 'true')}") 2722 2723 default = self.sql(expression, "default") 2724 2725 if default: 2726 statements.append(f"ELSE {default}") 2727 2728 statements.append("END") 2729 2730 if self.pretty and self.too_wide(statements): 2731 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2732 2733 return " ".join(statements)
2750 def trim_sql(self, expression: exp.Trim) -> str: 2751 trim_type = self.sql(expression, "position") 2752 2753 if trim_type == "LEADING": 2754 func_name = "LTRIM" 2755 elif trim_type == "TRAILING": 2756 func_name = "RTRIM" 2757 else: 2758 func_name = "TRIM" 2759 2760 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]:
2762 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2763 args = expression.expressions 2764 if isinstance(expression, exp.ConcatWs): 2765 args = args[1:] # Skip the delimiter 2766 2767 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2768 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2769 2770 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2771 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2772 2773 return args
2775 def concat_sql(self, expression: exp.Concat) -> str: 2776 expressions = self.convert_concat_args(expression) 2777 2778 # Some dialects don't allow a single-argument CONCAT call 2779 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2780 return self.sql(expressions[0]) 2781 2782 return self.func("CONCAT", *expressions)
2793 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2794 expressions = self.expressions(expression, flat=True) 2795 reference = self.sql(expression, "reference") 2796 reference = f" {reference}" if reference else "" 2797 delete = self.sql(expression, "delete") 2798 delete = f" ON DELETE {delete}" if delete else "" 2799 update = self.sql(expression, "update") 2800 update = f" ON UPDATE {update}" if update else "" 2801 return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"
2803 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2804 expressions = self.expressions(expression, flat=True) 2805 options = self.expressions(expression, key="options", flat=True, sep=" ") 2806 options = f" {options}" if options else "" 2807 return f"PRIMARY KEY ({expressions}){options}"
2820 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2821 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2822 2823 if expression.args.get("escape"): 2824 path = self.escape_str(path) 2825 2826 if self.QUOTE_JSON_PATH: 2827 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2828 2829 return path
2831 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2832 if isinstance(expression, exp.JSONPathPart): 2833 transform = self.TRANSFORMS.get(expression.__class__) 2834 if not callable(transform): 2835 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2836 return "" 2837 2838 return transform(self, expression) 2839 2840 if isinstance(expression, int): 2841 return str(expression) 2842 2843 if self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2844 escaped = expression.replace("'", "\\'") 2845 escaped = f"\\'{expression}\\'" 2846 else: 2847 escaped = expression.replace('"', '\\"') 2848 escaped = f'"{escaped}"' 2849 2850 return escaped
def
jsonobject_sql( self, expression: sqlglot.expressions.JSONObject | sqlglot.expressions.JSONObjectAgg) -> str:
2855 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2856 null_handling = expression.args.get("null_handling") 2857 null_handling = f" {null_handling}" if null_handling else "" 2858 2859 unique_keys = expression.args.get("unique_keys") 2860 if unique_keys is not None: 2861 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2862 else: 2863 unique_keys = "" 2864 2865 return_type = self.sql(expression, "return_type") 2866 return_type = f" RETURNING {return_type}" if return_type else "" 2867 encoding = self.sql(expression, "encoding") 2868 encoding = f" ENCODING {encoding}" if encoding else "" 2869 2870 return self.func( 2871 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2872 *expression.expressions, 2873 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2874 )
2879 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2880 null_handling = expression.args.get("null_handling") 2881 null_handling = f" {null_handling}" if null_handling else "" 2882 return_type = self.sql(expression, "return_type") 2883 return_type = f" RETURNING {return_type}" if return_type else "" 2884 strict = " STRICT" if expression.args.get("strict") else "" 2885 return self.func( 2886 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2887 )
2889 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2890 this = self.sql(expression, "this") 2891 order = self.sql(expression, "order") 2892 null_handling = expression.args.get("null_handling") 2893 null_handling = f" {null_handling}" if null_handling else "" 2894 return_type = self.sql(expression, "return_type") 2895 return_type = f" RETURNING {return_type}" if return_type else "" 2896 strict = " STRICT" if expression.args.get("strict") else "" 2897 return self.func( 2898 "JSON_ARRAYAGG", 2899 this, 2900 suffix=f"{order}{null_handling}{return_type}{strict})", 2901 )
2903 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2904 path = self.sql(expression, "path") 2905 path = f" PATH {path}" if path else "" 2906 nested_schema = self.sql(expression, "nested_schema") 2907 2908 if nested_schema: 2909 return f"NESTED{path} {nested_schema}" 2910 2911 this = self.sql(expression, "this") 2912 kind = self.sql(expression, "kind") 2913 kind = f" {kind}" if kind else "" 2914 return f"{this}{kind}{path}"
2919 def jsontable_sql(self, expression: exp.JSONTable) -> str: 2920 this = self.sql(expression, "this") 2921 path = self.sql(expression, "path") 2922 path = f", {path}" if path else "" 2923 error_handling = expression.args.get("error_handling") 2924 error_handling = f" {error_handling}" if error_handling else "" 2925 empty_handling = expression.args.get("empty_handling") 2926 empty_handling = f" {empty_handling}" if empty_handling else "" 2927 schema = self.sql(expression, "schema") 2928 return self.func( 2929 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 2930 )
2932 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 2933 this = self.sql(expression, "this") 2934 kind = self.sql(expression, "kind") 2935 path = self.sql(expression, "path") 2936 path = f" {path}" if path else "" 2937 as_json = " AS JSON" if expression.args.get("as_json") else "" 2938 return f"{this} {kind}{path}{as_json}"
2940 def openjson_sql(self, expression: exp.OpenJSON) -> str: 2941 this = self.sql(expression, "this") 2942 path = self.sql(expression, "path") 2943 path = f", {path}" if path else "" 2944 expressions = self.expressions(expression) 2945 with_ = ( 2946 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 2947 if expressions 2948 else "" 2949 ) 2950 return f"OPENJSON({this}{path}){with_}"
2952 def in_sql(self, expression: exp.In) -> str: 2953 query = expression.args.get("query") 2954 unnest = expression.args.get("unnest") 2955 field = expression.args.get("field") 2956 is_global = " GLOBAL" if expression.args.get("is_global") else "" 2957 2958 if query: 2959 in_sql = self.sql(query) 2960 elif unnest: 2961 in_sql = self.in_unnest_op(unnest) 2962 elif field: 2963 in_sql = self.sql(field) 2964 else: 2965 in_sql = f"({self.expressions(expression, flat=True)})" 2966 2967 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
2972 def interval_sql(self, expression: exp.Interval) -> str: 2973 unit = self.sql(expression, "unit") 2974 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 2975 unit = self.TIME_PART_SINGULARS.get(unit, unit) 2976 unit = f" {unit}" if unit else "" 2977 2978 if self.SINGLE_STRING_INTERVAL: 2979 this = expression.this.name if expression.this else "" 2980 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 2981 2982 this = self.sql(expression, "this") 2983 if this: 2984 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 2985 this = f" {this}" if unwrapped else f" ({this})" 2986 2987 return f"INTERVAL{this}{unit}"
2992 def reference_sql(self, expression: exp.Reference) -> str: 2993 this = self.sql(expression, "this") 2994 expressions = self.expressions(expression, flat=True) 2995 expressions = f"({expressions})" if expressions else "" 2996 options = self.expressions(expression, key="options", flat=True, sep=" ") 2997 options = f" {options}" if options else "" 2998 return f"REFERENCES {this}{expressions}{options}"
3000 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3001 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3002 parent = expression.parent 3003 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3004 return self.func( 3005 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3006 )
3026 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3027 alias = expression.args["alias"] 3028 3029 identifier_alias = isinstance(alias, exp.Identifier) 3030 literal_alias = isinstance(alias, exp.Literal) 3031 3032 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3033 alias.replace(exp.Literal.string(alias.output_name)) 3034 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3035 alias.replace(exp.to_identifier(alias.output_name)) 3036 3037 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:
3075 def connector_sql( 3076 self, 3077 expression: exp.Connector, 3078 op: str, 3079 stack: t.Optional[t.List[str | exp.Expression]] = None, 3080 ) -> str: 3081 if stack is not None: 3082 if expression.expressions: 3083 stack.append(self.expressions(expression, sep=f" {op} ")) 3084 else: 3085 stack.append(expression.right) 3086 if expression.comments and self.comments: 3087 for comment in expression.comments: 3088 if comment: 3089 op += f" /*{self.pad_comment(comment)}*/" 3090 stack.extend((op, expression.left)) 3091 return op 3092 3093 stack = [expression] 3094 sqls: t.List[str] = [] 3095 ops = set() 3096 3097 while stack: 3098 node = stack.pop() 3099 if isinstance(node, exp.Connector): 3100 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3101 else: 3102 sql = self.sql(node) 3103 if sqls and sqls[-1] in ops: 3104 sqls[-1] += f" {sql}" 3105 else: 3106 sqls.append(sql) 3107 3108 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3109 return sep.join(sqls)
def
cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str:
3129 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3130 format_sql = self.sql(expression, "format") 3131 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3132 to_sql = self.sql(expression, "to") 3133 to_sql = f" {to_sql}" if to_sql else "" 3134 action = self.sql(expression, "action") 3135 action = f" {action}" if action else "" 3136 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})"
3150 def comment_sql(self, expression: exp.Comment) -> str: 3151 this = self.sql(expression, "this") 3152 kind = expression.args["kind"] 3153 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3154 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3155 expression_sql = self.sql(expression, "expression") 3156 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
3158 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3159 this = self.sql(expression, "this") 3160 delete = " DELETE" if expression.args.get("delete") else "" 3161 recompress = self.sql(expression, "recompress") 3162 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3163 to_disk = self.sql(expression, "to_disk") 3164 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3165 to_volume = self.sql(expression, "to_volume") 3166 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3167 return f"{this}{delete}{recompress}{to_disk}{to_volume}"
3169 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3170 where = self.sql(expression, "where") 3171 group = self.sql(expression, "group") 3172 aggregates = self.expressions(expression, key="aggregates") 3173 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3174 3175 if not (where or group or aggregates) and len(expression.expressions) == 1: 3176 return f"TTL {self.expressions(expression, flat=True)}" 3177 3178 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
3195 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3196 this = self.sql(expression, "this") 3197 3198 dtype = self.sql(expression, "dtype") 3199 if dtype: 3200 collate = self.sql(expression, "collate") 3201 collate = f" COLLATE {collate}" if collate else "" 3202 using = self.sql(expression, "using") 3203 using = f" USING {using}" if using else "" 3204 return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}" 3205 3206 default = self.sql(expression, "default") 3207 if default: 3208 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3209 3210 comment = self.sql(expression, "comment") 3211 if comment: 3212 return f"ALTER COLUMN {this} COMMENT {comment}" 3213 3214 allow_null = expression.args.get("allow_null") 3215 drop = expression.args.get("drop") 3216 3217 if not drop and not allow_null: 3218 self.unsupported("Unsupported ALTER COLUMN syntax") 3219 3220 if allow_null is not None: 3221 keyword = "DROP" if drop else "SET" 3222 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3223 3224 return f"ALTER COLUMN {this} DROP DEFAULT"
3232 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3233 compound = " COMPOUND" if expression.args.get("compound") else "" 3234 this = self.sql(expression, "this") 3235 expressions = self.expressions(expression, flat=True) 3236 expressions = f"({expressions})" if expressions else "" 3237 return f"ALTER{compound} SORTKEY {this or expressions}"
3239 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3240 if not self.RENAME_TABLE_WITH_DB: 3241 # Remove db from tables 3242 expression = expression.transform( 3243 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3244 ).assert_is(exp.AlterRename) 3245 this = self.sql(expression, "this") 3246 return f"RENAME TO {this}"
3258 def alter_sql(self, expression: exp.Alter) -> str: 3259 actions = expression.args["actions"] 3260 3261 if isinstance(actions[0], exp.ColumnDef): 3262 actions = self.add_column_sql(expression) 3263 elif isinstance(actions[0], exp.Schema): 3264 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3265 elif isinstance(actions[0], exp.Delete): 3266 actions = self.expressions(expression, key="actions", flat=True) 3267 elif isinstance(actions[0], exp.Query): 3268 actions = "AS " + self.expressions(expression, key="actions") 3269 else: 3270 actions = self.expressions(expression, key="actions", flat=True) 3271 3272 exists = " IF EXISTS" if expression.args.get("exists") else "" 3273 on_cluster = self.sql(expression, "cluster") 3274 on_cluster = f" {on_cluster}" if on_cluster else "" 3275 only = " ONLY" if expression.args.get("only") else "" 3276 options = self.expressions(expression, key="options") 3277 options = f", {options}" if options else "" 3278 kind = self.sql(expression, "kind") 3279 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3280 3281 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
3283 def add_column_sql(self, expression: exp.Alter) -> str: 3284 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3285 return self.expressions( 3286 expression, 3287 key="actions", 3288 prefix="ADD COLUMN ", 3289 skip_first=True, 3290 ) 3291 return f"ADD {self.expressions(expression, key='actions', flat=True)}"
3301 def distinct_sql(self, expression: exp.Distinct) -> str: 3302 this = self.expressions(expression, flat=True) 3303 3304 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3305 case = exp.case() 3306 for arg in expression.expressions: 3307 case = case.when(arg.is_(exp.null()), exp.null()) 3308 this = self.sql(case.else_(f"({this})")) 3309 3310 this = f" {this}" if this else "" 3311 3312 on = self.sql(expression, "on") 3313 on = f" ON {on}" if on else "" 3314 return f"DISTINCT{this}{on}"
3343 def div_sql(self, expression: exp.Div) -> str: 3344 l, r = expression.left, expression.right 3345 3346 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3347 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3348 3349 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3350 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3351 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3352 3353 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3354 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3355 return self.sql( 3356 exp.cast( 3357 l / r, 3358 to=exp.DataType.Type.BIGINT, 3359 ) 3360 ) 3361 3362 return self.binary(expression, "/")
3450 def log_sql(self, expression: exp.Log) -> str: 3451 this = expression.this 3452 expr = expression.expression 3453 3454 if self.dialect.LOG_BASE_FIRST is False: 3455 this, expr = expr, this 3456 elif self.dialect.LOG_BASE_FIRST is None and expr: 3457 if this.name in ("2", "10"): 3458 return self.func(f"LOG{this.name}", expr) 3459 3460 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3461 3462 return self.func("LOG", this, expr)
3471 def binary(self, expression: exp.Binary, op: str) -> str: 3472 sqls: t.List[str] = [] 3473 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3474 binary_type = type(expression) 3475 3476 while stack: 3477 node = stack.pop() 3478 3479 if type(node) is binary_type: 3480 op_func = node.args.get("operator") 3481 if op_func: 3482 op = f"OPERATOR({self.sql(op_func)})" 3483 3484 stack.append(node.right) 3485 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3486 stack.append(node.left) 3487 else: 3488 sqls.append(self.sql(node)) 3489 3490 return "".join(sqls)
3492 def function_fallback_sql(self, expression: exp.Func) -> str: 3493 args = [] 3494 3495 for key in expression.arg_types: 3496 arg_value = expression.args.get(key) 3497 3498 if isinstance(arg_value, list): 3499 for value in arg_value: 3500 args.append(value) 3501 elif arg_value is not None: 3502 args.append(arg_value) 3503 3504 if self.normalize_functions: 3505 name = expression.sql_name() 3506 else: 3507 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3508 3509 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:
3511 def func( 3512 self, 3513 name: str, 3514 *args: t.Optional[exp.Expression | str], 3515 prefix: str = "(", 3516 suffix: str = ")", 3517 normalize: bool = True, 3518 ) -> str: 3519 name = self.normalize_func(name) if normalize else name 3520 return f"{name}{prefix}{self.format_args(*args)}{suffix}"
def
format_args( self, *args: Union[str, sqlglot.expressions.Expression, NoneType], sep: str = ', ') -> str:
3522 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3523 arg_sqls = tuple( 3524 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3525 ) 3526 if self.pretty and self.too_wide(arg_sqls): 3527 return self.indent( 3528 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3529 ) 3530 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]:
3535 def format_time( 3536 self, 3537 expression: exp.Expression, 3538 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3539 inverse_time_trie: t.Optional[t.Dict] = None, 3540 ) -> t.Optional[str]: 3541 return format_time( 3542 self.sql(expression, "format"), 3543 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3544 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3545 )
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:
3547 def expressions( 3548 self, 3549 expression: t.Optional[exp.Expression] = None, 3550 key: t.Optional[str] = None, 3551 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3552 flat: bool = False, 3553 indent: bool = True, 3554 skip_first: bool = False, 3555 skip_last: bool = False, 3556 sep: str = ", ", 3557 prefix: str = "", 3558 dynamic: bool = False, 3559 new_line: bool = False, 3560 ) -> str: 3561 expressions = expression.args.get(key or "expressions") if expression else sqls 3562 3563 if not expressions: 3564 return "" 3565 3566 if flat: 3567 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3568 3569 num_sqls = len(expressions) 3570 result_sqls = [] 3571 3572 for i, e in enumerate(expressions): 3573 sql = self.sql(e, comment=False) 3574 if not sql: 3575 continue 3576 3577 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3578 3579 if self.pretty: 3580 if self.leading_comma: 3581 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3582 else: 3583 result_sqls.append( 3584 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3585 ) 3586 else: 3587 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3588 3589 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3590 if new_line: 3591 result_sqls.insert(0, "") 3592 result_sqls.append("") 3593 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3594 else: 3595 result_sql = "".join(result_sqls) 3596 3597 return ( 3598 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3599 if indent 3600 else result_sql 3601 )
def
op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str:
3603 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3604 flat = flat or isinstance(expression.parent, exp.Properties) 3605 expressions_sql = self.expressions(expression, flat=flat) 3606 if flat: 3607 return f"{op} {expressions_sql}" 3608 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
3610 def naked_property(self, expression: exp.Property) -> str: 3611 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3612 if not property_name: 3613 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3614 return f"{property_name} {self.sql(expression, 'this')}"
3622 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3623 this = self.sql(expression, "this") 3624 expressions = self.no_identify(self.expressions, expression) 3625 expressions = ( 3626 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3627 ) 3628 return f"{this}{expressions}" if expressions.strip() != "" else this
3638 def when_sql(self, expression: exp.When) -> str: 3639 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3640 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3641 condition = self.sql(expression, "condition") 3642 condition = f" AND {condition}" if condition else "" 3643 3644 then_expression = expression.args.get("then") 3645 if isinstance(then_expression, exp.Insert): 3646 this = self.sql(then_expression, "this") 3647 this = f"INSERT {this}" if this else "INSERT" 3648 then = self.sql(then_expression, "expression") 3649 then = f"{this} VALUES {then}" if then else this 3650 elif isinstance(then_expression, exp.Update): 3651 if isinstance(then_expression.args.get("expressions"), exp.Star): 3652 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3653 else: 3654 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3655 else: 3656 then = self.sql(then_expression) 3657 return f"WHEN {matched}{source}{condition} THEN {then}"
3659 def merge_sql(self, expression: exp.Merge) -> str: 3660 table = expression.this 3661 table_alias = "" 3662 3663 hints = table.args.get("hints") 3664 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3665 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3666 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3667 3668 this = self.sql(table) 3669 using = f"USING {self.sql(expression, 'using')}" 3670 on = f"ON {self.sql(expression, 'on')}" 3671 expressions = self.expressions(expression, sep=" ", indent=False) 3672 returning = self.sql(expression, "returning") 3673 if returning: 3674 expressions = f"{expressions}{returning}" 3675 3676 sep = self.sep() 3677 3678 return self.prepend_ctes( 3679 expression, 3680 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}", 3681 )
3687 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3688 if not self.SUPPORTS_TO_NUMBER: 3689 self.unsupported("Unsupported TO_NUMBER function") 3690 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3691 3692 fmt = expression.args.get("format") 3693 if not fmt: 3694 self.unsupported("Conversion format is required for TO_NUMBER") 3695 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3696 3697 return self.func("TO_NUMBER", expression.this, fmt)
3699 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3700 this = self.sql(expression, "this") 3701 kind = self.sql(expression, "kind") 3702 settings_sql = self.expressions(expression, key="settings", sep=" ") 3703 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3704 return f"{this}({kind}{args})"
3719 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3720 expressions = self.expressions(expression, flat=True) 3721 expressions = f" {self.wrap(expressions)}" if expressions else "" 3722 buckets = self.sql(expression, "buckets") 3723 kind = self.sql(expression, "kind") 3724 buckets = f" BUCKETS {buckets}" if buckets else "" 3725 order = self.sql(expression, "order") 3726 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
3731 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3732 expressions = self.expressions(expression, key="expressions", flat=True) 3733 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3734 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3735 buckets = self.sql(expression, "buckets") 3736 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
3738 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3739 this = self.sql(expression, "this") 3740 having = self.sql(expression, "having") 3741 3742 if having: 3743 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3744 3745 return self.func("ANY_VALUE", this)
3747 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3748 transform = self.func("TRANSFORM", *expression.expressions) 3749 row_format_before = self.sql(expression, "row_format_before") 3750 row_format_before = f" {row_format_before}" if row_format_before else "" 3751 record_writer = self.sql(expression, "record_writer") 3752 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3753 using = f" USING {self.sql(expression, 'command_script')}" 3754 schema = self.sql(expression, "schema") 3755 schema = f" AS {schema}" if schema else "" 3756 row_format_after = self.sql(expression, "row_format_after") 3757 row_format_after = f" {row_format_after}" if row_format_after else "" 3758 record_reader = self.sql(expression, "record_reader") 3759 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3760 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
3762 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3763 key_block_size = self.sql(expression, "key_block_size") 3764 if key_block_size: 3765 return f"KEY_BLOCK_SIZE = {key_block_size}" 3766 3767 using = self.sql(expression, "using") 3768 if using: 3769 return f"USING {using}" 3770 3771 parser = self.sql(expression, "parser") 3772 if parser: 3773 return f"WITH PARSER {parser}" 3774 3775 comment = self.sql(expression, "comment") 3776 if comment: 3777 return f"COMMENT {comment}" 3778 3779 visible = expression.args.get("visible") 3780 if visible is not None: 3781 return "VISIBLE" if visible else "INVISIBLE" 3782 3783 engine_attr = self.sql(expression, "engine_attr") 3784 if engine_attr: 3785 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3786 3787 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3788 if secondary_engine_attr: 3789 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3790 3791 self.unsupported("Unsupported index constraint option.") 3792 return ""
3798 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3799 kind = self.sql(expression, "kind") 3800 kind = f"{kind} INDEX" if kind else "INDEX" 3801 this = self.sql(expression, "this") 3802 this = f" {this}" if this else "" 3803 index_type = self.sql(expression, "index_type") 3804 index_type = f" USING {index_type}" if index_type else "" 3805 expressions = self.expressions(expression, flat=True) 3806 expressions = f" ({expressions})" if expressions else "" 3807 options = self.expressions(expression, key="options", sep=" ") 3808 options = f" {options}" if options else "" 3809 return f"{kind}{this}{index_type}{expressions}{options}"
3811 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3812 if self.NVL2_SUPPORTED: 3813 return self.function_fallback_sql(expression) 3814 3815 case = exp.Case().when( 3816 expression.this.is_(exp.null()).not_(copy=False), 3817 expression.args["true"], 3818 copy=False, 3819 ) 3820 else_cond = expression.args.get("false") 3821 if else_cond: 3822 case.else_(else_cond, copy=False) 3823 3824 return self.sql(case)
3826 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3827 this = self.sql(expression, "this") 3828 expr = self.sql(expression, "expression") 3829 iterator = self.sql(expression, "iterator") 3830 condition = self.sql(expression, "condition") 3831 condition = f" IF {condition}" if condition else "" 3832 return f"{this} FOR {expr} IN {iterator}{condition}"
3840 def predict_sql(self, expression: exp.Predict) -> str: 3841 model = self.sql(expression, "this") 3842 model = f"MODEL {model}" 3843 table = self.sql(expression, "expression") 3844 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3845 parameters = self.sql(expression, "params_struct") 3846 return self.func("PREDICT", model, table, parameters or None)
3858 def toarray_sql(self, expression: exp.ToArray) -> str: 3859 arg = expression.this 3860 if not arg.type: 3861 from sqlglot.optimizer.annotate_types import annotate_types 3862 3863 arg = annotate_types(arg) 3864 3865 if arg.is_type(exp.DataType.Type.ARRAY): 3866 return self.sql(arg) 3867 3868 cond_for_null = arg.is_(exp.null()) 3869 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
3885 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 3886 this = expression.this 3887 time_format = self.format_time(expression) 3888 3889 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 3890 return self.sql( 3891 exp.cast( 3892 exp.StrToTime(this=this, format=expression.args["format"]), 3893 exp.DataType.Type.DATE, 3894 ) 3895 ) 3896 3897 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 3898 return self.sql(this) 3899 3900 return self.sql(exp.cast(this, exp.DataType.Type.DATE))
3912 def lastday_sql(self, expression: exp.LastDay) -> str: 3913 if self.LAST_DAY_SUPPORTS_DATE_PART: 3914 return self.function_fallback_sql(expression) 3915 3916 unit = expression.text("unit") 3917 if unit and unit != "MONTH": 3918 self.unsupported("Date parts are not supported in LAST_DAY.") 3919 3920 return self.func("LAST_DAY", expression.this)
3929 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 3930 if self.CAN_IMPLEMENT_ARRAY_ANY: 3931 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 3932 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 3933 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 3934 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 3935 3936 from sqlglot.dialects import Dialect 3937 3938 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 3939 if self.dialect.__class__ != Dialect: 3940 self.unsupported("ARRAY_ANY is unsupported") 3941 3942 return self.function_fallback_sql(expression)
3944 def struct_sql(self, expression: exp.Struct) -> str: 3945 expression.set( 3946 "expressions", 3947 [ 3948 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 3949 if isinstance(e, exp.PropertyEQ) 3950 else e 3951 for e in expression.expressions 3952 ], 3953 ) 3954 3955 return self.function_fallback_sql(expression)
3963 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 3964 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 3965 tables = f" {self.expressions(expression)}" 3966 3967 exists = " IF EXISTS" if expression.args.get("exists") else "" 3968 3969 on_cluster = self.sql(expression, "cluster") 3970 on_cluster = f" {on_cluster}" if on_cluster else "" 3971 3972 identity = self.sql(expression, "identity") 3973 identity = f" {identity} IDENTITY" if identity else "" 3974 3975 option = self.sql(expression, "option") 3976 option = f" {option}" if option else "" 3977 3978 partition = self.sql(expression, "partition") 3979 partition = f" {partition}" if partition else "" 3980 3981 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
3985 def convert_sql(self, expression: exp.Convert) -> str: 3986 to = expression.this 3987 value = expression.expression 3988 style = expression.args.get("style") 3989 safe = expression.args.get("safe") 3990 strict = expression.args.get("strict") 3991 3992 if not to or not value: 3993 return "" 3994 3995 # Retrieve length of datatype and override to default if not specified 3996 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 3997 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 3998 3999 transformed: t.Optional[exp.Expression] = None 4000 cast = exp.Cast if strict else exp.TryCast 4001 4002 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4003 if isinstance(style, exp.Literal) and style.is_int: 4004 from sqlglot.dialects.tsql import TSQL 4005 4006 style_value = style.name 4007 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4008 if not converted_style: 4009 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4010 4011 fmt = exp.Literal.string(converted_style) 4012 4013 if to.this == exp.DataType.Type.DATE: 4014 transformed = exp.StrToDate(this=value, format=fmt) 4015 elif to.this == exp.DataType.Type.DATETIME: 4016 transformed = exp.StrToTime(this=value, format=fmt) 4017 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4018 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4019 elif to.this == exp.DataType.Type.TEXT: 4020 transformed = exp.TimeToStr(this=value, format=fmt) 4021 4022 if not transformed: 4023 transformed = cast(this=value, to=to, safe=safe) 4024 4025 return self.sql(transformed)
4081 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4082 option = self.sql(expression, "this") 4083 4084 if expression.expressions: 4085 upper = option.upper() 4086 4087 # Snowflake FILE_FORMAT options are separated by whitespace 4088 sep = " " if upper == "FILE_FORMAT" else ", " 4089 4090 # Databricks copy/format options do not set their list of values with EQ 4091 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4092 values = self.expressions(expression, flat=True, sep=sep) 4093 return f"{option}{op}({values})" 4094 4095 value = self.sql(expression, "expression") 4096 4097 if not value: 4098 return option 4099 4100 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4101 4102 return f"{option}{op}{value}"
4104 def credentials_sql(self, expression: exp.Credentials) -> str: 4105 cred_expr = expression.args.get("credentials") 4106 if isinstance(cred_expr, exp.Literal): 4107 # Redshift case: CREDENTIALS <string> 4108 credentials = self.sql(expression, "credentials") 4109 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4110 else: 4111 # Snowflake case: CREDENTIALS = (...) 4112 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4113 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4114 4115 storage = self.sql(expression, "storage") 4116 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4117 4118 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4119 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4120 4121 iam_role = self.sql(expression, "iam_role") 4122 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4123 4124 region = self.sql(expression, "region") 4125 region = f" REGION {region}" if region else "" 4126 4127 return f"{credentials}{storage}{encryption}{iam_role}{region}"
4129 def copy_sql(self, expression: exp.Copy) -> str: 4130 this = self.sql(expression, "this") 4131 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4132 4133 credentials = self.sql(expression, "credentials") 4134 credentials = self.seg(credentials) if credentials else "" 4135 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4136 files = self.expressions(expression, key="files", flat=True) 4137 4138 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4139 params = self.expressions( 4140 expression, 4141 key="params", 4142 sep=sep, 4143 new_line=True, 4144 skip_last=True, 4145 skip_first=True, 4146 indent=self.COPY_PARAMS_ARE_WRAPPED, 4147 ) 4148 4149 if params: 4150 if self.COPY_PARAMS_ARE_WRAPPED: 4151 params = f" WITH ({params})" 4152 elif not self.pretty: 4153 params = f" {params}" 4154 4155 return f"COPY{this}{kind} {files}{credentials}{params}"
4160 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4161 on_sql = "ON" if expression.args.get("on") else "OFF" 4162 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4163 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4164 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4165 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4166 4167 if filter_col or retention_period: 4168 on_sql = self.func("ON", filter_col, retention_period) 4169 4170 return f"DATA_DELETION={on_sql}"
def
maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.MaskingPolicyColumnConstraint) -> str:
4172 def maskingpolicycolumnconstraint_sql( 4173 self, expression: exp.MaskingPolicyColumnConstraint 4174 ) -> str: 4175 this = self.sql(expression, "this") 4176 expressions = self.expressions(expression, flat=True) 4177 expressions = f" USING ({expressions})" if expressions else "" 4178 return f"MASKING POLICY {this}{expressions}"
4188 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4189 this = self.sql(expression, "this") 4190 expr = expression.expression 4191 4192 if isinstance(expr, exp.Func): 4193 # T-SQL's CLR functions are case sensitive 4194 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4195 else: 4196 expr = self.sql(expression, "expression") 4197 4198 return self.scope_resolution(expr, this)
4206 def rand_sql(self, expression: exp.Rand) -> str: 4207 lower = self.sql(expression, "lower") 4208 upper = self.sql(expression, "upper") 4209 4210 if lower and upper: 4211 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4212 return self.func("RAND", expression.this)
4214 def changes_sql(self, expression: exp.Changes) -> str: 4215 information = self.sql(expression, "information") 4216 information = f"INFORMATION => {information}" 4217 at_before = self.sql(expression, "at_before") 4218 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4219 end = self.sql(expression, "end") 4220 end = f"{self.seg('')}{end}" if end else "" 4221 4222 return f"CHANGES ({information}){at_before}{end}"
4224 def pad_sql(self, expression: exp.Pad) -> str: 4225 prefix = "L" if expression.args.get("is_left") else "R" 4226 4227 fill_pattern = self.sql(expression, "fill_pattern") or None 4228 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4229 fill_pattern = "' '" 4230 4231 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
def
explodinggenerateseries_sql(self, expression: sqlglot.expressions.ExplodingGenerateSeries) -> str:
4237 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4238 generate_series = exp.GenerateSeries(**expression.args) 4239 4240 parent = expression.parent 4241 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4242 parent = parent.parent 4243 4244 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4245 return self.sql(exp.Unnest(expressions=[generate_series])) 4246 4247 if isinstance(parent, exp.Select): 4248 self.unsupported("GenerateSeries projection unnesting is not supported.") 4249 4250 return self.sql(generate_series)
def
arrayconcat_sql( self, expression: sqlglot.expressions.ArrayConcat, name: str = 'ARRAY_CONCAT') -> str:
4252 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4253 exprs = expression.expressions 4254 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4255 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4256 else: 4257 rhs = self.expressions(expression) 4258 4259 return self.func(name, expression.this, rhs or None)
4261 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4262 if self.SUPPORTS_CONVERT_TIMEZONE: 4263 return self.function_fallback_sql(expression) 4264 4265 source_tz = expression.args.get("source_tz") 4266 target_tz = expression.args.get("target_tz") 4267 timestamp = expression.args.get("timestamp") 4268 4269 if source_tz and timestamp: 4270 timestamp = exp.AtTimeZone( 4271 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4272 ) 4273 4274 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4275 4276 return self.sql(expr)
4278 def json_sql(self, expression: exp.JSON) -> str: 4279 this = self.sql(expression, "this") 4280 this = f" {this}" if this else "" 4281 4282 _with = expression.args.get("with") 4283 4284 if _with is None: 4285 with_sql = "" 4286 elif not _with: 4287 with_sql = " WITHOUT" 4288 else: 4289 with_sql = " WITH" 4290 4291 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4292 4293 return f"JSON{this}{with_sql}{unique_sql}"
4295 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4296 def _generate_on_options(arg: t.Any) -> str: 4297 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4298 4299 path = self.sql(expression, "path") 4300 returning = self.sql(expression, "returning") 4301 returning = f" RETURNING {returning}" if returning else "" 4302 4303 on_condition = self.sql(expression, "on_condition") 4304 on_condition = f" {on_condition}" if on_condition else "" 4305 4306 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
4308 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4309 else_ = "ELSE " if expression.args.get("else_") else "" 4310 condition = self.sql(expression, "expression") 4311 condition = f"WHEN {condition} THEN " if condition else else_ 4312 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4313 return f"{condition}{insert}"
4321 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4322 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4323 empty = expression.args.get("empty") 4324 empty = ( 4325 f"DEFAULT {empty} ON EMPTY" 4326 if isinstance(empty, exp.Expression) 4327 else self.sql(expression, "empty") 4328 ) 4329 4330 error = expression.args.get("error") 4331 error = ( 4332 f"DEFAULT {error} ON ERROR" 4333 if isinstance(error, exp.Expression) 4334 else self.sql(expression, "error") 4335 ) 4336 4337 if error and empty: 4338 error = ( 4339 f"{empty} {error}" 4340 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4341 else f"{error} {empty}" 4342 ) 4343 empty = "" 4344 4345 null = self.sql(expression, "null") 4346 4347 return f"{empty}{error}{null}"
4349 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4350 this = self.sql(expression, "this") 4351 path = self.sql(expression, "path") 4352 4353 passing = self.expressions(expression, "passing") 4354 passing = f" PASSING {passing}" if passing else "" 4355 4356 on_condition = self.sql(expression, "on_condition") 4357 on_condition = f" {on_condition}" if on_condition else "" 4358 4359 path = f"{path}{passing}{on_condition}" 4360 4361 return self.func("JSON_EXISTS", this, path)
4363 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4364 array_agg = self.function_fallback_sql(expression) 4365 4366 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4367 parent = expression.parent 4368 if isinstance(parent, exp.Filter): 4369 parent_cond = parent.expression.this 4370 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4371 else: 4372 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4373 this = expression.this 4374 this_sql = ( 4375 self.expressions(this) 4376 if isinstance(this, exp.Distinct) 4377 else self.sql(expression, "this") 4378 ) 4379 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4380 4381 return array_agg
4389 def grant_sql(self, expression: exp.Grant) -> str: 4390 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4391 4392 kind = self.sql(expression, "kind") 4393 kind = f" {kind}" if kind else "" 4394 4395 securable = self.sql(expression, "securable") 4396 securable = f" {securable}" if securable else "" 4397 4398 principals = self.expressions(expression, key="principals", flat=True) 4399 4400 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4401 4402 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
4426 def overlay_sql(self, expression: exp.Overlay): 4427 this = self.sql(expression, "this") 4428 expr = self.sql(expression, "expression") 4429 from_sql = self.sql(expression, "from") 4430 for_sql = self.sql(expression, "for") 4431 for_sql = f" FOR {for_sql}" if for_sql else "" 4432 4433 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
@unsupported_args('format')
def
todouble_sql(self, expression: sqlglot.expressions.ToDouble) -> str:
4439 def string_sql(self, expression: exp.String) -> str: 4440 this = expression.this 4441 zone = expression.args.get("zone") 4442 4443 if zone: 4444 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4445 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4446 # set for source_tz to transpile the time conversion before the STRING cast 4447 this = exp.ConvertTimezone( 4448 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4449 ) 4450 4451 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))