Edit on GitHub

sqlglot.generators.tsql

  1from __future__ import annotations
  2
  3from functools import reduce
  4
  5from sqlglot import exp, generator, transforms
  6from sqlglot.dialects.dialect import (
  7    any_value_to_max_sql,
  8    date_delta_sql,
  9    datestrtodate_sql,
 10    generatedasidentitycolumnconstraint_sql,
 11    max_or_greatest,
 12    min_or_least,
 13    no_filter_sql,
 14    remove_ts_or_ds_to_date,
 15    rename_func,
 16    strposition_sql,
 17    timestrtotime_sql,
 18    trim_sql,
 19    unit_to_var,
 20)
 21from sqlglot.helper import seq_get
 22from sqlglot.optimizer.scope import find_in_scope
 23from sqlglot.parsers.tsql import OPTIONS_THAT_REQUIRE_EQUAL
 24from sqlglot.time import format_time
 25from collections import defaultdict
 26
 27DATE_PART_UNMAPPING = {
 28    "ISOWEEK": "ISO_WEEK",
 29    "WEEKISO": "ISO_WEEK",
 30    "DAYOFWEEK": "WEEKDAY",
 31    "TIMEZONE_MINUTE": "TZOFFSET",
 32}
 33
 34BIT_TYPES = {exp.EQ, exp.NEQ, exp.Is, exp.In, exp.Select, exp.Alias}
 35
 36SET_OP_MODIFIERS = ("limit", "offset", "order", "for_", "options")
 37
 38
 39def _format_sql(self: TSQLGenerator, expression: exp.NumberToStr | exp.TimeToStr) -> str:
 40    fmt = expression.args["format"]
 41
 42    if not isinstance(expression, exp.NumberToStr):
 43        if fmt.is_string:
 44            from sqlglot.dialects.tsql import TSQL
 45
 46            mapped_fmt = format_time(fmt.name, TSQL.INVERSE_TIME_MAPPING)
 47            fmt_sql = self.sql(exp.Literal.string(mapped_fmt))
 48        else:
 49            fmt_sql = self.format_time(expression) or self.sql(fmt)
 50    else:
 51        fmt_sql = self.sql(fmt)
 52
 53    return self.func("FORMAT", expression.this, fmt_sql, expression.args.get("culture"))
 54
 55
 56def _sha2_sql(self: TSQLGenerator, expression: exp.SHA2 | exp.SHA2Digest) -> str:
 57    return self.func(
 58        "HASHBYTES",
 59        exp.Literal.string(f"SHA2_{expression.args.get('length', 256)}"),
 60        expression.this,
 61    )
 62
 63
 64def _string_agg_sql(self: TSQLGenerator, expression: exp.GroupConcat) -> str:
 65    this = expression.this
 66    distinct = find_in_scope(expression, exp.Distinct)
 67    if distinct:
 68        # exp.Distinct can appear below an exp.Order or an exp.GroupConcat expression
 69        self.unsupported("T-SQL STRING_AGG doesn't support DISTINCT.")
 70        this = distinct.pop().expressions[0]
 71
 72    order = ""
 73    if isinstance(expression.this, exp.Order):
 74        if expression.this.this:
 75            this = expression.this.this.pop()
 76        # Order has a leading space
 77        order = f" WITHIN GROUP ({self.sql(expression.this)[1:]})"
 78
 79    separator = expression.args.get("separator") or exp.Literal.string(",")
 80    return f"STRING_AGG({self.format_args(this, separator)}){order}"
 81
 82
 83def qualify_derived_table_outputs(expression: exp.Expr) -> exp.Expr:
 84    """Ensures all (unnamed) output columns are aliased for CTEs and Subqueries."""
 85    alias = expression.args.get("alias")
 86
 87    if (
 88        isinstance(expression, (exp.CTE, exp.Subquery))
 89        and isinstance(alias, exp.TableAlias)
 90        and not alias.columns
 91        and isinstance(expression.this, exp.Query)
 92    ):
 93        from sqlglot.dialects.tsql import TSQL
 94        from sqlglot.optimizer.qualify_columns import qualify_outputs
 95
 96        # We keep track of the unaliased column projection indexes instead of the expressions
 97        # themselves, because the latter are going to be replaced by new nodes when the aliases
 98        # are added and hence we won't be able to reach these newly added Alias parents
 99        query = expression.this
100        unaliased_column_indexes = (
101            i for i, c in enumerate(query.selects) if isinstance(c, exp.Column) and not c.alias
102        )
103
104        qualify_outputs(query, dialect=TSQL())
105
106        # Preserve the quoting information of columns for newly added Alias nodes
107        query_selects = query.selects
108        for select_index in unaliased_column_indexes:
109            alias = query_selects[select_index]
110            column = alias.this
111            if isinstance(column.this, exp.Identifier):
112                alias.args["alias"].set("quoted", column.this.quoted)
113
114    return expression
115
116
117def _json_extract_sql(
118    self: TSQLGenerator, expression: exp.JSONExtract | exp.JSONExtractScalar
119) -> str:
120    # JSON_QUERY returns objects and arrays, JSON_VALUE returns scalars. A scalar-only
121    # extraction maps to JSON_VALUE; a source that also returns non-scalar values as
122    # text (e.g. SQLite's ->>) needs to try both, like a generic JSONExtract does
123    if isinstance(expression, exp.JSONExtractScalar) and expression.args.get("scalar_only"):
124        return self.func("JSON_VALUE", expression.this, expression.expression)
125
126    json_query = self.func("JSON_QUERY", expression.this, expression.expression)
127    if expression.args.get("json_query"):
128        return json_query
129
130    json_value = self.func("JSON_VALUE", expression.this, expression.expression)
131    return self.func("ISNULL", json_query, json_value)
132
133
134def _timestrtotime_sql(self: TSQLGenerator, expression: exp.TimeStrToTime):
135    sql = timestrtotime_sql(self, expression)
136    if expression.args.get("zone"):
137        # If there is a timezone, produce an expression like:
138        # CAST('2020-01-01 12:13:14-08:00' AS DATETIMEOFFSET) AT TIME ZONE 'UTC'
139        # If you dont have AT TIME ZONE 'UTC', wrapping that expression in another cast back to DATETIME2 just drops the timezone information
140        return self.sql(exp.AtTimeZone(this=sql, zone=exp.Literal.string("UTC")))
141    return sql
142
143
144class TSQLGenerator(generator.Generator):
145    SELECT_KINDS = ()
146    TRY_SUPPORTED = False
147    SUPPORTS_UESCAPE = False
148    SUPPORTS_DECODE_CASE = False
149    SUPPORTS_MULTI_ARG_CHR = False
150
151    AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
152
153    LIMIT_IS_TOP = True
154    SET_OP_LIMITS = True
155    QUERY_HINTS = False
156    RETURNING_END = False
157    NVL2_SUPPORTED = False
158    ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
159    ALTER_TABLE_ADD_COLUMNS_WRAPPED = False
160    LIMIT_FETCH = "FETCH"
161    COMPUTED_COLUMN_WITH_TYPE = False
162    CTE_RECURSIVE_KEYWORD_REQUIRED = False
163    ENSURE_BOOLS = True
164    NULL_ORDERING_SUPPORTED: bool | None = None
165    SUPPORTS_SINGLE_ARG_CONCAT = False
166    TABLESAMPLE_SEED_KEYWORD = "REPEATABLE"
167    SUPPORTS_SELECT_INTO = True
168    JSON_PATH_BRACKETED_KEY_SUPPORTED = False
169    SUPPORTS_TO_NUMBER = False
170    COPY_PARAMS_EQ_REQUIRED = True
171    PARSE_JSON_NAME: str | None = None
172    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
173    ALTER_SET_WRAPPED = True
174    ALTER_SET_TYPE = ""
175    SUPPORTS_ALTER_COLUMN_NULLABILITY = True
176
177    EXPRESSIONS_WITHOUT_NESTED_CTES = {
178        exp.Create,
179        exp.Delete,
180        exp.Insert,
181        exp.Intersect,
182        exp.Except,
183        exp.Merge,
184        exp.Select,
185        exp.Subquery,
186        exp.Union,
187        exp.Update,
188    }
189
190    SUPPORTED_JSON_PATH_PARTS = {
191        exp.JSONPathKey,
192        exp.JSONPathRoot,
193        exp.JSONPathSubscript,
194    }
195
196    TYPE_MAPPING = {
197        **{
198            k: v
199            for k, v in generator.Generator.TYPE_MAPPING.items()
200            if k not in (exp.DType.NCHAR, exp.DType.NVARCHAR)
201        },
202        exp.DType.BOOLEAN: "BIT",
203        exp.DType.DATETIME2: "DATETIME2",
204        exp.DType.DECIMAL: "NUMERIC",
205        exp.DType.DOUBLE: "FLOAT",
206        exp.DType.INT: "INTEGER",
207        exp.DType.ROWVERSION: "ROWVERSION",
208        exp.DType.TEXT: "VARCHAR(MAX)",
209        exp.DType.TIMESTAMP: "DATETIME2",
210        exp.DType.TIMESTAMPNTZ: "DATETIME2",
211        exp.DType.TIMESTAMPTZ: "DATETIMEOFFSET",
212        exp.DType.SMALLDATETIME: "SMALLDATETIME",
213        exp.DType.TINYINT: "SMALLINT",
214        exp.DType.UTINYINT: "TINYINT",
215        exp.DType.VARIANT: "SQL_VARIANT",
216        exp.DType.UUID: "UNIQUEIDENTIFIER",
217    }
218
219    TRANSFORMS = {
220        **{k: v for k, v in generator.Generator.TRANSFORMS.items() if k != exp.ReturnsProperty},
221        exp.AnyValue: any_value_to_max_sql,
222        exp.Atan2: rename_func("ATN2"),
223        exp.ArrayToString: rename_func("STRING_AGG"),
224        exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
225        exp.Ceil: rename_func("CEILING"),
226        exp.Chr: lambda self, e: self.chr_sql(e, "CHAR"),
227        exp.DateAdd: date_delta_sql("DATEADD"),
228        exp.CTE: transforms.preprocess([qualify_derived_table_outputs]),
229        exp.CurrentDate: rename_func("GETDATE"),
230        exp.CurrentTimestamp: rename_func("GETDATE"),
231        exp.CurrentTimestampLTZ: rename_func("SYSDATETIMEOFFSET"),
232        exp.DateStrToDate: datestrtodate_sql,
233        exp.Day: remove_ts_or_ds_to_date(),
234        exp.Filter: no_filter_sql,
235        exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
236        exp.GroupConcat: _string_agg_sql,
237        exp.If: rename_func("IIF"),
238        exp.JSONExtract: _json_extract_sql,
239        exp.JSONExtractScalar: _json_extract_sql,
240        exp.LastDay: lambda self, e: self.func("EOMONTH", e.this),
241        exp.Ln: rename_func("LOG"),
242        exp.Max: max_or_greatest,
243        exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
244        exp.Min: min_or_least,
245        exp.Month: remove_ts_or_ds_to_date(),
246        exp.NumberToStr: _format_sql,
247        exp.Repeat: rename_func("REPLICATE"),
248        exp.CurrentSchema: rename_func("SCHEMA_NAME"),
249        exp.Select: transforms.preprocess(
250            [
251                transforms.eliminate_distinct_on,
252                transforms.eliminate_semi_and_anti_joins,
253                transforms.eliminate_qualify,
254                transforms.unnest_generate_date_array_using_recursive_cte,
255            ]
256        ),
257        exp.Stddev: rename_func("STDEV"),
258        exp.StrPosition: lambda self, e: strposition_sql(
259            self, e, func_name="CHARINDEX", supports_position=True
260        ),
261        exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]),
262        exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
263        exp.SHA1Digest: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
264        exp.SHA2: _sha2_sql,
265        exp.SHA2Digest: _sha2_sql,
266        exp.TemporaryProperty: lambda self, e: "",
267        exp.TimeStrToTime: _timestrtotime_sql,
268        exp.TimeToStr: _format_sql,
269        exp.TimestampAdd: date_delta_sql("DATEADD"),
270        exp.Trim: trim_sql,
271        exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
272        exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
273        exp.TimestampTrunc: lambda self, e: self.func("DATETRUNC", e.unit, e.this),
274        exp.Trunc: lambda self, e: self.func(
275            "ROUND",
276            e.this,
277            e.args.get("decimals") or exp.Literal.number(0),
278            exp.Literal.number(1),
279        ),
280        exp.Uuid: lambda *_: "NEWID()",
281        exp.Year: remove_ts_or_ds_to_date(),
282        exp.DateFromParts: rename_func("DATEFROMPARTS"),
283        exp.DayOfYear: lambda self, e: self.func("DATEPART", "DAYOFYEAR", e.this),
284    }
285
286    PROPERTIES_LOCATION = {
287        **generator.Generator.PROPERTIES_LOCATION,
288        exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
289    }
290
291    def scope_resolution(self, rhs: str, scope_name: str) -> str:
292        return f"{scope_name}::{rhs}"
293
294    # Inline unsupported check: mypyc cannot compile @unsupported_args on an
295    # override of an undecorated base-class method.
296    def datetrunc_sql(self, expression: exp.DateTrunc) -> str:
297        self._warn_unsupported_arg(expression, "zone")
298        self._warn_unsupported_arg(expression, "century_from_zero")
299        unit_expr = expression.unit
300        if isinstance(unit_expr, exp.WeekStart):
301            unit: exp.Expr | None = exp.var(
302                "ISO_WEEK" if unit_expr.name.upper() == "MONDAY" else self.weekstart_name(unit_expr)
303            )
304        else:
305            if unit_expr.is_string and unit_expr.name.upper() in ("WEEK_OF_MONTH", "WEEK_OF_YEAR"):
306                self.unsupported(f"Unexpected interval unit: {unit_expr.name}")
307            unit = unit_to_var(expression)
308            if isinstance(unit, exp.Var) and unit.name.upper() == "ISOWEEK":
309                unit = exp.var("ISO_WEEK")
310        return self.func("DATETRUNC", unit, expression.this)
311
312    def select_sql(self, expression: exp.Select) -> str:
313        self._prepare_limit_offset(expression)
314
315        # Handles transpiling a query like the following to T-SQL:
316        #   SELECT 1 AS x ORDER BY x NULLS FIRST FETCH FIRST 1 ROWS ONLY UNION ALL SELECT 2 AS x
317        if isinstance(expression.parent, exp.SetOperation) and isinstance(
318            expression.args.get("limit"), exp.Fetch
319        ):
320            return self.sql(
321                exp.select("*").from_(expression.subquery("_l_0", copy=False), copy=False)
322            )
323
324        return super().select_sql(expression)
325
326    def set_operations(self, expression: exp.SetOperation) -> str:
327        limit = expression.args.get("limit")
328        offset = expression.args.get("offset")
329        order = expression.args.get("order")
330
331        # Set operations cannot order by the CASE used to emulate null ordering,
332        # or by expressions that aren't in their select list.
333        wrap_order = False
334        if order:
335            selects = {select.unalias().unnest() for select in expression.selects}
336            for ordered in order.expressions:
337                this = ordered.this.unnest()
338                if this.is_int:
339                    continue
340
341                desc = ordered.args.get("desc")
342                nulls_first = ordered.args.get("nulls_first")
343
344                emulate_null_ordering = (desc and nulls_first) or (not desc and not nulls_first)
345                if emulate_null_ordering or (
346                    not isinstance(this, exp.Column) and this not in selects
347                ):
348                    wrap_order = True
349                    break
350
351        if (
352            wrap_order
353            or (isinstance(limit, exp.Limit) and not offset)
354            or (not order and (offset or isinstance(limit, exp.Fetch)))
355        ):
356            select = self._move_ctes_to_top_level(
357                exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
358            )
359            for arg in SET_OP_MODIFIERS:
360                value = expression.args.get(arg)
361                if value:
362                    expression.set(arg, None)
363                    select.set(arg, value)
364
365            return self.sql(select)
366
367        self._prepare_limit_offset(expression)
368        return super().set_operations(expression)
369
370    def _prepare_limit_offset(self, expression: exp.Query) -> None:
371        limit = expression.args.get("limit")
372        offset = expression.args.get("offset")
373
374        if isinstance(limit, exp.Fetch) and not offset:
375            # Dialects like Oracle can FETCH directly from a row set but
376            # T-SQL requires an ORDER BY + OFFSET clause in order to FETCH
377            offset = exp.Offset(expression=exp.Literal.number(0))
378            expression.set("offset", offset)
379
380        if offset:
381            if not expression.args.get("order"):
382                # ORDER BY is required in order to use OFFSET in a query, so we use
383                # a noop order by, since we don't really care about the order.
384                # See: https://www.microsoftpressstore.com/articles/article.aspx?p=2314819
385                expression.order_by(exp.select(exp.null()).subquery(), copy=False)
386
387            if isinstance(limit, exp.Limit) and not limit.is_limit_all:
388                # TOP and OFFSET can't be combined, we need use FETCH instead of TOP
389                # we replace here because otherwise TOP would be generated in select_sql
390                limit.replace(exp.Fetch(direction="FIRST", count=limit.expression))
391
392    def convert_sql(self, expression: exp.Convert) -> str:
393        name = "TRY_CONVERT" if expression.args.get("safe") else "CONVERT"
394        return self.func(name, expression.this, expression.expression, expression.args.get("style"))
395
396    def queryoption_sql(self, expression: exp.QueryOption) -> str:
397        option = self.sql(expression, "this")
398        value = self.sql(expression, "expression")
399        if value:
400            optional_equal_sign = "= " if option in OPTIONS_THAT_REQUIRE_EQUAL else ""
401            return f"{option} {optional_equal_sign}{value}"
402        return option
403
404    def lateral_op(self, expression: exp.Lateral) -> str:
405        cross_apply = expression.args.get("cross_apply")
406        if cross_apply is True:
407            return "CROSS APPLY"
408        if cross_apply is False:
409            return "OUTER APPLY"
410
411        # TODO: perhaps we can check if the parent is a Join and transpile it appropriately
412        self.unsupported("LATERAL clause is not supported.")
413        return "LATERAL"
414
415    def splitpart_sql(self, expression: exp.SplitPart) -> str:
416        this = expression.this
417        split_count = len(this.name.split("."))
418        delimiter = expression.args.get("delimiter")
419        part_index = expression.args.get("part_index")
420
421        if (
422            not all(isinstance(arg, exp.Literal) for arg in (this, delimiter, part_index))
423            or (delimiter and delimiter.name != ".")
424            or not part_index
425            or split_count > 4
426        ):
427            self.unsupported(
428                "SPLIT_PART can be transpiled to PARSENAME only for '.' delimiter and literal values"
429            )
430            return ""
431
432        return self.func(
433            "PARSENAME", this, exp.Literal.number(split_count + 1 - part_index.to_py())
434        )
435
436    def _native_dayofweek_sql(self, expression: exp.DayOfWeek) -> str:
437        return self.func("DATEPART", "WEEKDAY", expression.this)
438
439    def extract_sql(self, expression: exp.Extract) -> str:
440        if expression.args.get("uses_session_timezone") and expression.expression.is_type(
441            exp.DType.TIMESTAMPTZ
442        ):
443            self.unsupported(
444                f"Extracting {expression.this.name.upper()} from TIMESTAMPTZ depends on the source session time zone. "
445                "Use AT TIME ZONE on the input to make the time zone explicit."
446            )
447
448        if expression.args.get("zero_based_dow"):
449            # The earliest SQL Server date was a Monday, so the dividend is always positive.
450            days = exp.DateDiff(
451                this=exp.cast(expression.expression, exp.DType.DATE, dialect=self.dialect),
452                expression=exp.Literal.string("00010101"),
453                unit=exp.var("DAY"),
454            )
455            result: exp.Expr = (days + 1) % 7
456        else:
457            part = expression.this
458            name = ""
459            if not expression.args.get("date_part") or isinstance(part, (exp.Var, exp.Literal)):
460                name = part.name.upper()
461            if name != "DOY":
462                return self.func(
463                    "DATEPART", DATE_PART_UNMAPPING.get(name) or part, expression.expression
464                )
465            result = exp.DayOfYear(this=expression.expression.copy())
466
467        if expression.type and not expression.is_type(exp.DType.INT, exp.DType.UNKNOWN):
468            result = exp.cast(result, expression.type, copy=False)
469        elif isinstance(result, exp.Mod):
470            result = exp.paren(result, copy=False)
471        return self.sql(result)
472
473    def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
474        nano = expression.args.get("nano")
475        if nano is not None:
476            nano.pop()
477            self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.")
478
479        if expression.args.get("fractions") is None:
480            expression.set("fractions", exp.Literal.number(0))
481        if expression.args.get("precision") is None:
482            expression.set("precision", exp.Literal.number(0))
483
484        return rename_func("TIMEFROMPARTS")(self, expression)
485
486    def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str:
487        zone = expression.args.get("zone")
488        if zone is not None:
489            zone.pop()
490            self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.")
491
492        nano = expression.args.get("nano")
493        if nano is not None:
494            nano.pop()
495            self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.")
496
497        if expression.args.get("milli") is None:
498            expression.set("milli", exp.Literal.number(0))
499
500        return rename_func("DATETIMEFROMPARTS")(self, expression)
501
502    def setitem_sql(self, expression: exp.SetItem) -> str:
503        this = expression.this
504        if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
505            # T-SQL does not use '=' in SET command, except when the LHS is a variable.
506            return f"{self.sql(this.left)} {self.sql(this.right)}"
507
508        return super().setitem_sql(expression)
509
510    def boolean_sql(self, expression: exp.Boolean) -> str:
511        if type(expression.parent) in BIT_TYPES or isinstance(
512            expression.find_ancestor(exp.Values, exp.Select), exp.Values
513        ):
514            return "1" if expression.this else "0"
515
516        return "(1 = 1)" if expression.this else "(1 = 0)"
517
518    def is_sql(self, expression: exp.Is) -> str:
519        negate = expression.args.get("negate")
520        if isinstance(expression.expression, exp.Boolean):
521            return self.binary(expression, "<>" if negate else "=")
522        return self.binary(expression, "IS NOT" if negate else "IS")
523
524    def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str:
525        sql = self.sql(expression, "this")
526        properties = expression.args.get("properties")
527
528        start = self._identifier_start
529        if (
530            not sql.startswith("#")
531            and not sql.startswith(f"{start}#")
532            and any(
533                isinstance(prop, exp.TemporaryProperty)
534                for prop in (properties.expressions if properties else [])
535            )
536        ):
537            sql = f"{start}#{sql[len(start) :]}" if sql.startswith(start) else f"#{sql}"
538
539        return sql
540
541    def create_sql(self, expression: exp.Create) -> str:
542        kind = expression.kind
543        exists = expression.args.get("exists")
544        expression.set("exists", None)
545
546        like_property = expression.find(exp.LikeProperty)
547        if like_property:
548            ctas_expression = like_property.this
549        else:
550            ctas_expression = expression.expression
551
552        if kind == "VIEW":
553            expression.this.set("catalog", None)
554            with_ = expression.args.get("with_")
555            if ctas_expression and with_:
556                # We've already preprocessed the Create expression to bubble up any nested CTEs,
557                # but CREATE VIEW actually requires the WITH clause to come after it so we need
558                # to amend the AST by moving the CTEs to the CREATE VIEW statement's query.
559                ctas_expression.set("with_", with_.pop())
560        elif (
561            kind == "FUNCTION"
562            and isinstance(ctas_expression, exp.Return)
563            and isinstance(body := ctas_expression.this.unnest(), exp.Query)
564            and (with_ := expression.args.get("with_"))
565        ):
566            # Similar to the VIEW branch, the table-valued functions require the WITH clause
567            # to stay inside the RETURN body, so we move back any CTEs that were bubbled up.
568            body.set("with_", with_.pop())
569
570        table = expression.find(exp.Table)
571
572        # Convert CTAS statement to SELECT .. INTO ..
573        if kind == "TABLE" and ctas_expression:
574            if isinstance(ctas_expression, exp.UNWRAPPED_QUERIES):
575                ctas_expression = ctas_expression.subquery()
576
577            properties = expression.args.get("properties") or exp.Properties()
578            is_temp = any(isinstance(p, exp.TemporaryProperty) for p in properties.expressions)
579
580            select_into = exp.select("*").from_(exp.alias_(ctas_expression, "temp", table=True))
581            select_into.set("into", exp.Into(this=table, temporary=is_temp))
582
583            if like_property:
584                select_into.limit(0, copy=False)
585
586            sql = self.sql(select_into)
587        else:
588            sql = super().create_sql(expression)
589
590        if exists:
591            identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
592            sql_with_ctes = self.prepend_ctes(expression, sql)
593            sql_literal = self.sql(exp.Literal.string(sql_with_ctes))
594            if kind == "SCHEMA":
595                return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = {identifier}) EXEC({sql_literal})"""
596            elif kind == "TABLE":
597                assert table
598                where = exp.and_(
599                    exp.column("TABLE_NAME").eq(table.name),
600                    exp.column("TABLE_SCHEMA").eq(table.db) if table.db else None,
601                    exp.column("TABLE_CATALOG").eq(table.catalog) if table.catalog else None,
602                )
603                return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE {where}) EXEC({sql_literal})"""
604            elif kind == "INDEX":
605                index = self.sql(exp.Literal.string(expression.this.text("this")))
606                return f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql_literal})"""
607        elif expression.args.get("replace"):
608            sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
609
610        return self.prepend_ctes(expression, sql)
611
612    @generator.unsupported_args("unlogged", "expressions")
613    def into_sql(self, expression: exp.Into) -> str:
614        if expression.args.get("temporary"):
615            # If the Into expression has a temporary property, push this down to the Identifier
616            table = expression.find(exp.Table)
617            if table and isinstance(table.this, exp.Identifier):
618                table.this.set("temporary", True)
619
620        return f"{self.seg('INTO')} {self.sql(expression, 'this')}"
621
622    def count_sql(self, expression: exp.Count) -> str:
623        func_name = "COUNT_BIG" if expression.args.get("big_int") else "COUNT"
624        return rename_func(func_name)(self, expression)
625
626    def countif_sql(self, expression: exp.CountIf) -> str:
627        # T-SQL has no COUNT_IF, so count the rows where the predicate holds instead
628        return self.func(
629            "COUNT", exp.If(this=expression.this, true=exp.Literal.number(1), false=exp.null())
630        )
631
632    def datediff_sql(self, expression: exp.DateDiff) -> str:
633        func_name = "DATEDIFF_BIG" if expression.args.get("big_int") else "DATEDIFF"
634        return date_delta_sql(func_name)(self, expression)
635
636    def offset_sql(self, expression: exp.Offset) -> str:
637        return f"{super().offset_sql(expression)} ROWS"
638
639    def version_sql(self, expression: exp.Version) -> str:
640        name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
641        this = f"FOR {name}"
642        expr = expression.expression
643        kind = expression.text("kind")
644        if kind in ("FROM", "BETWEEN"):
645            args = expr.expressions
646            sep = "TO" if kind == "FROM" else "AND"
647            expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
648        else:
649            expr_sql = self.sql(expr)
650
651        expr_sql = f" {expr_sql}" if expr_sql else ""
652        return f"{this} {kind}{expr_sql}"
653
654    def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
655        table = expression.args.get("table")
656        table = f"{table} " if table else ""
657        return f"RETURNS {table}{self.sql(expression, 'this')}"
658
659    def returning_sql(self, expression: exp.Returning) -> str:
660        into = self.sql(expression, "into")
661        into = self.seg(f"INTO {into}") if into else ""
662        return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
663
664    def transaction_sql(self, expression: exp.Transaction) -> str:
665        this = self.sql(expression, "this")
666        this = f" {this}" if this else ""
667        mark = self.sql(expression, "mark")
668        mark = f" WITH MARK {mark}" if mark else ""
669        return f"BEGIN TRANSACTION{this}{mark}"
670
671    def commit_sql(self, expression: exp.Commit) -> str:
672        this = self.sql(expression, "this")
673        this = f" {this}" if this else ""
674        durability = expression.args.get("durability")
675        durability = (
676            f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
677            if durability is not None
678            else ""
679        )
680        return f"COMMIT TRANSACTION{this}{durability}"
681
682    def rollback_sql(self, expression: exp.Rollback) -> str:
683        this = self.sql(expression, "this")
684        this = f" {this}" if this else ""
685        return f"ROLLBACK TRANSACTION{this}"
686
687    def identifier_sql(self, expression: exp.Identifier) -> str:
688        identifier = super().identifier_sql(expression)
689
690        if expression.args.get("global_"):
691            prefix = "##"
692        elif expression.args.get("temporary"):
693            prefix = "#"
694        else:
695            return identifier
696
697        start = self._identifier_start
698        if expression.quoted and identifier.startswith(start):
699            return f"{start}{prefix}{identifier[len(start) :]}"
700
701        return f"{prefix}{identifier}"
702
703    def constraint_sql(self, expression: exp.Constraint) -> str:
704        this = self.sql(expression, "this")
705        expressions = self.expressions(expression, flat=True, sep=" ")
706        return f"CONSTRAINT {this} {expressions}"
707
708    def length_sql(self, expression: exp.Length) -> str:
709        return self._uncast_text(expression, "LEN")
710
711    def right_sql(self, expression: exp.Right) -> str:
712        return self._uncast_text(expression, "RIGHT")
713
714    def left_sql(self, expression: exp.Left) -> str:
715        return self._uncast_text(expression, "LEFT")
716
717    def _uncast_text(self, expression: exp.Expr, name: str) -> str:
718        this = expression.this
719        if isinstance(this, exp.Cast) and this.is_type(exp.DType.TEXT):
720            this_sql = self.sql(this, "this")
721        else:
722            this_sql = self.sql(this)
723        expression_sql = self.sql(expression, "expression")
724        return self.func(name, this_sql, expression_sql if expression_sql else None)
725
726    def partition_sql(self, expression: exp.Partition) -> str:
727        return f"WITH (PARTITIONS({self.expressions(expression, flat=True)}))"
728
729    def alter_sql(self, expression: exp.Alter) -> str:
730        actions = expression.args.get("actions") or []
731        if len(actions) == 1 and isinstance(actions[0], exp.AlterRename):
732            old_name = self.sql(exp.Literal.string(self.sql(expression.this)))
733            new_name = self.sql(exp.Literal.string(actions[0].this.name))
734            return f"EXEC sp_rename {old_name}, {new_name}"
735        return super().alter_sql(expression)
736
737    def drop_sql(self, expression: exp.Drop) -> str:
738        if expression.args["kind"] == "VIEW":
739            for table in expression.args.get("tables") or []:
740                table.set("catalog", None)
741        return super().drop_sql(expression)
742
743    def options_modifier(self, expression: exp.Expr) -> str:
744        options = self.expressions(expression, key="options")
745        return f" OPTION{self.wrap(options)}" if options else ""
746
747    def dpipe_sql(self, expression: exp.DPipe) -> str:
748        return self.sql(reduce(lambda x, y: exp.Add(this=x, expression=y), expression.flatten()))
749
750    def isascii_sql(self, expression: exp.IsAscii) -> str:
751        return f"(PATINDEX(CONVERT(VARCHAR(MAX), 0x255b5e002d7f5d25) COLLATE Latin1_General_BIN, {self.sql(expression.this)}) = 0)"
752
753    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
754        this = super().columndef_sql(expression, sep)
755        default = self.sql(expression, "default")
756        default = f" = {default}" if default else ""
757        output = self.sql(expression, "output")
758        output = f" {output}" if output else ""
759        return f"{this}{default}{output}"
760
761    def coalesce_sql(self, expression: exp.Coalesce) -> str:
762        func_name = "ISNULL" if expression.args.get("is_null") else "COALESCE"
763        return rename_func(func_name)(self, expression)
764
765    def storedprocedure_sql(self, expression: exp.StoredProcedure) -> str:
766        this = self.sql(expression, "this")
767        expressions = self.expressions(expression)
768        expressions = (
769            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
770        )
771        return f"{this}{expressions}" if expressions.strip() != "" else this
772
773    def ifblock_sql(self, expression: exp.IfBlock) -> str:
774        this = self.sql(expression, "this")
775        true = self.sql(expression, "true")
776        true = f" {true}" if true else " "
777        false = self.sql(expression, "false")
778        false = f"; ELSE BEGIN {false}" if false else ""
779        return f"IF {this} BEGIN{true}{false}"
780
781    def whileblock_sql(self, expression: exp.WhileBlock) -> str:
782        this = self.sql(expression, "this")
783        body = self.sql(expression, "body")
784        body = f" {body}" if body else " "
785        return f"WHILE {this} BEGIN{body}"
786
787    def execute_sql(self, expression: exp.Execute) -> str:
788        this = self.sql(expression, "this")
789        expressions = self.expressions(expression)
790        expressions = f" {expressions}" if expressions else ""
791        return_status = self.sql(expression, "return_status")
792        return_status = f"{return_status} = " if return_status else ""
793        return f"EXECUTE {return_status}{this}{expressions}"
794
795    def executesql_sql(self, expression: exp.ExecuteSql) -> str:
796        return self.execute_sql(expression)
DATE_PART_UNMAPPING = {'ISOWEEK': 'ISO_WEEK', 'WEEKISO': 'ISO_WEEK', 'DAYOFWEEK': 'WEEKDAY', 'TIMEZONE_MINUTE': 'TZOFFSET'}
SET_OP_MODIFIERS = ('limit', 'offset', 'order', 'for_', 'options')
def qualify_derived_table_outputs( expression: sqlglot.expressions.core.Expr) -> sqlglot.expressions.core.Expr:
 84def qualify_derived_table_outputs(expression: exp.Expr) -> exp.Expr:
 85    """Ensures all (unnamed) output columns are aliased for CTEs and Subqueries."""
 86    alias = expression.args.get("alias")
 87
 88    if (
 89        isinstance(expression, (exp.CTE, exp.Subquery))
 90        and isinstance(alias, exp.TableAlias)
 91        and not alias.columns
 92        and isinstance(expression.this, exp.Query)
 93    ):
 94        from sqlglot.dialects.tsql import TSQL
 95        from sqlglot.optimizer.qualify_columns import qualify_outputs
 96
 97        # We keep track of the unaliased column projection indexes instead of the expressions
 98        # themselves, because the latter are going to be replaced by new nodes when the aliases
 99        # are added and hence we won't be able to reach these newly added Alias parents
100        query = expression.this
101        unaliased_column_indexes = (
102            i for i, c in enumerate(query.selects) if isinstance(c, exp.Column) and not c.alias
103        )
104
105        qualify_outputs(query, dialect=TSQL())
106
107        # Preserve the quoting information of columns for newly added Alias nodes
108        query_selects = query.selects
109        for select_index in unaliased_column_indexes:
110            alias = query_selects[select_index]
111            column = alias.this
112            if isinstance(column.this, exp.Identifier):
113                alias.args["alias"].set("quoted", column.this.quoted)
114
115    return expression

Ensures all (unnamed) output columns are aliased for CTEs and Subqueries.

class TSQLGenerator(sqlglot.generator.Generator):
145class TSQLGenerator(generator.Generator):
146    SELECT_KINDS = ()
147    TRY_SUPPORTED = False
148    SUPPORTS_UESCAPE = False
149    SUPPORTS_DECODE_CASE = False
150    SUPPORTS_MULTI_ARG_CHR = False
151
152    AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
153
154    LIMIT_IS_TOP = True
155    SET_OP_LIMITS = True
156    QUERY_HINTS = False
157    RETURNING_END = False
158    NVL2_SUPPORTED = False
159    ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
160    ALTER_TABLE_ADD_COLUMNS_WRAPPED = False
161    LIMIT_FETCH = "FETCH"
162    COMPUTED_COLUMN_WITH_TYPE = False
163    CTE_RECURSIVE_KEYWORD_REQUIRED = False
164    ENSURE_BOOLS = True
165    NULL_ORDERING_SUPPORTED: bool | None = None
166    SUPPORTS_SINGLE_ARG_CONCAT = False
167    TABLESAMPLE_SEED_KEYWORD = "REPEATABLE"
168    SUPPORTS_SELECT_INTO = True
169    JSON_PATH_BRACKETED_KEY_SUPPORTED = False
170    SUPPORTS_TO_NUMBER = False
171    COPY_PARAMS_EQ_REQUIRED = True
172    PARSE_JSON_NAME: str | None = None
173    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
174    ALTER_SET_WRAPPED = True
175    ALTER_SET_TYPE = ""
176    SUPPORTS_ALTER_COLUMN_NULLABILITY = True
177
178    EXPRESSIONS_WITHOUT_NESTED_CTES = {
179        exp.Create,
180        exp.Delete,
181        exp.Insert,
182        exp.Intersect,
183        exp.Except,
184        exp.Merge,
185        exp.Select,
186        exp.Subquery,
187        exp.Union,
188        exp.Update,
189    }
190
191    SUPPORTED_JSON_PATH_PARTS = {
192        exp.JSONPathKey,
193        exp.JSONPathRoot,
194        exp.JSONPathSubscript,
195    }
196
197    TYPE_MAPPING = {
198        **{
199            k: v
200            for k, v in generator.Generator.TYPE_MAPPING.items()
201            if k not in (exp.DType.NCHAR, exp.DType.NVARCHAR)
202        },
203        exp.DType.BOOLEAN: "BIT",
204        exp.DType.DATETIME2: "DATETIME2",
205        exp.DType.DECIMAL: "NUMERIC",
206        exp.DType.DOUBLE: "FLOAT",
207        exp.DType.INT: "INTEGER",
208        exp.DType.ROWVERSION: "ROWVERSION",
209        exp.DType.TEXT: "VARCHAR(MAX)",
210        exp.DType.TIMESTAMP: "DATETIME2",
211        exp.DType.TIMESTAMPNTZ: "DATETIME2",
212        exp.DType.TIMESTAMPTZ: "DATETIMEOFFSET",
213        exp.DType.SMALLDATETIME: "SMALLDATETIME",
214        exp.DType.TINYINT: "SMALLINT",
215        exp.DType.UTINYINT: "TINYINT",
216        exp.DType.VARIANT: "SQL_VARIANT",
217        exp.DType.UUID: "UNIQUEIDENTIFIER",
218    }
219
220    TRANSFORMS = {
221        **{k: v for k, v in generator.Generator.TRANSFORMS.items() if k != exp.ReturnsProperty},
222        exp.AnyValue: any_value_to_max_sql,
223        exp.Atan2: rename_func("ATN2"),
224        exp.ArrayToString: rename_func("STRING_AGG"),
225        exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
226        exp.Ceil: rename_func("CEILING"),
227        exp.Chr: lambda self, e: self.chr_sql(e, "CHAR"),
228        exp.DateAdd: date_delta_sql("DATEADD"),
229        exp.CTE: transforms.preprocess([qualify_derived_table_outputs]),
230        exp.CurrentDate: rename_func("GETDATE"),
231        exp.CurrentTimestamp: rename_func("GETDATE"),
232        exp.CurrentTimestampLTZ: rename_func("SYSDATETIMEOFFSET"),
233        exp.DateStrToDate: datestrtodate_sql,
234        exp.Day: remove_ts_or_ds_to_date(),
235        exp.Filter: no_filter_sql,
236        exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
237        exp.GroupConcat: _string_agg_sql,
238        exp.If: rename_func("IIF"),
239        exp.JSONExtract: _json_extract_sql,
240        exp.JSONExtractScalar: _json_extract_sql,
241        exp.LastDay: lambda self, e: self.func("EOMONTH", e.this),
242        exp.Ln: rename_func("LOG"),
243        exp.Max: max_or_greatest,
244        exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
245        exp.Min: min_or_least,
246        exp.Month: remove_ts_or_ds_to_date(),
247        exp.NumberToStr: _format_sql,
248        exp.Repeat: rename_func("REPLICATE"),
249        exp.CurrentSchema: rename_func("SCHEMA_NAME"),
250        exp.Select: transforms.preprocess(
251            [
252                transforms.eliminate_distinct_on,
253                transforms.eliminate_semi_and_anti_joins,
254                transforms.eliminate_qualify,
255                transforms.unnest_generate_date_array_using_recursive_cte,
256            ]
257        ),
258        exp.Stddev: rename_func("STDEV"),
259        exp.StrPosition: lambda self, e: strposition_sql(
260            self, e, func_name="CHARINDEX", supports_position=True
261        ),
262        exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]),
263        exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
264        exp.SHA1Digest: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
265        exp.SHA2: _sha2_sql,
266        exp.SHA2Digest: _sha2_sql,
267        exp.TemporaryProperty: lambda self, e: "",
268        exp.TimeStrToTime: _timestrtotime_sql,
269        exp.TimeToStr: _format_sql,
270        exp.TimestampAdd: date_delta_sql("DATEADD"),
271        exp.Trim: trim_sql,
272        exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
273        exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
274        exp.TimestampTrunc: lambda self, e: self.func("DATETRUNC", e.unit, e.this),
275        exp.Trunc: lambda self, e: self.func(
276            "ROUND",
277            e.this,
278            e.args.get("decimals") or exp.Literal.number(0),
279            exp.Literal.number(1),
280        ),
281        exp.Uuid: lambda *_: "NEWID()",
282        exp.Year: remove_ts_or_ds_to_date(),
283        exp.DateFromParts: rename_func("DATEFROMPARTS"),
284        exp.DayOfYear: lambda self, e: self.func("DATEPART", "DAYOFYEAR", e.this),
285    }
286
287    PROPERTIES_LOCATION = {
288        **generator.Generator.PROPERTIES_LOCATION,
289        exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
290    }
291
292    def scope_resolution(self, rhs: str, scope_name: str) -> str:
293        return f"{scope_name}::{rhs}"
294
295    # Inline unsupported check: mypyc cannot compile @unsupported_args on an
296    # override of an undecorated base-class method.
297    def datetrunc_sql(self, expression: exp.DateTrunc) -> str:
298        self._warn_unsupported_arg(expression, "zone")
299        self._warn_unsupported_arg(expression, "century_from_zero")
300        unit_expr = expression.unit
301        if isinstance(unit_expr, exp.WeekStart):
302            unit: exp.Expr | None = exp.var(
303                "ISO_WEEK" if unit_expr.name.upper() == "MONDAY" else self.weekstart_name(unit_expr)
304            )
305        else:
306            if unit_expr.is_string and unit_expr.name.upper() in ("WEEK_OF_MONTH", "WEEK_OF_YEAR"):
307                self.unsupported(f"Unexpected interval unit: {unit_expr.name}")
308            unit = unit_to_var(expression)
309            if isinstance(unit, exp.Var) and unit.name.upper() == "ISOWEEK":
310                unit = exp.var("ISO_WEEK")
311        return self.func("DATETRUNC", unit, expression.this)
312
313    def select_sql(self, expression: exp.Select) -> str:
314        self._prepare_limit_offset(expression)
315
316        # Handles transpiling a query like the following to T-SQL:
317        #   SELECT 1 AS x ORDER BY x NULLS FIRST FETCH FIRST 1 ROWS ONLY UNION ALL SELECT 2 AS x
318        if isinstance(expression.parent, exp.SetOperation) and isinstance(
319            expression.args.get("limit"), exp.Fetch
320        ):
321            return self.sql(
322                exp.select("*").from_(expression.subquery("_l_0", copy=False), copy=False)
323            )
324
325        return super().select_sql(expression)
326
327    def set_operations(self, expression: exp.SetOperation) -> str:
328        limit = expression.args.get("limit")
329        offset = expression.args.get("offset")
330        order = expression.args.get("order")
331
332        # Set operations cannot order by the CASE used to emulate null ordering,
333        # or by expressions that aren't in their select list.
334        wrap_order = False
335        if order:
336            selects = {select.unalias().unnest() for select in expression.selects}
337            for ordered in order.expressions:
338                this = ordered.this.unnest()
339                if this.is_int:
340                    continue
341
342                desc = ordered.args.get("desc")
343                nulls_first = ordered.args.get("nulls_first")
344
345                emulate_null_ordering = (desc and nulls_first) or (not desc and not nulls_first)
346                if emulate_null_ordering or (
347                    not isinstance(this, exp.Column) and this not in selects
348                ):
349                    wrap_order = True
350                    break
351
352        if (
353            wrap_order
354            or (isinstance(limit, exp.Limit) and not offset)
355            or (not order and (offset or isinstance(limit, exp.Fetch)))
356        ):
357            select = self._move_ctes_to_top_level(
358                exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
359            )
360            for arg in SET_OP_MODIFIERS:
361                value = expression.args.get(arg)
362                if value:
363                    expression.set(arg, None)
364                    select.set(arg, value)
365
366            return self.sql(select)
367
368        self._prepare_limit_offset(expression)
369        return super().set_operations(expression)
370
371    def _prepare_limit_offset(self, expression: exp.Query) -> None:
372        limit = expression.args.get("limit")
373        offset = expression.args.get("offset")
374
375        if isinstance(limit, exp.Fetch) and not offset:
376            # Dialects like Oracle can FETCH directly from a row set but
377            # T-SQL requires an ORDER BY + OFFSET clause in order to FETCH
378            offset = exp.Offset(expression=exp.Literal.number(0))
379            expression.set("offset", offset)
380
381        if offset:
382            if not expression.args.get("order"):
383                # ORDER BY is required in order to use OFFSET in a query, so we use
384                # a noop order by, since we don't really care about the order.
385                # See: https://www.microsoftpressstore.com/articles/article.aspx?p=2314819
386                expression.order_by(exp.select(exp.null()).subquery(), copy=False)
387
388            if isinstance(limit, exp.Limit) and not limit.is_limit_all:
389                # TOP and OFFSET can't be combined, we need use FETCH instead of TOP
390                # we replace here because otherwise TOP would be generated in select_sql
391                limit.replace(exp.Fetch(direction="FIRST", count=limit.expression))
392
393    def convert_sql(self, expression: exp.Convert) -> str:
394        name = "TRY_CONVERT" if expression.args.get("safe") else "CONVERT"
395        return self.func(name, expression.this, expression.expression, expression.args.get("style"))
396
397    def queryoption_sql(self, expression: exp.QueryOption) -> str:
398        option = self.sql(expression, "this")
399        value = self.sql(expression, "expression")
400        if value:
401            optional_equal_sign = "= " if option in OPTIONS_THAT_REQUIRE_EQUAL else ""
402            return f"{option} {optional_equal_sign}{value}"
403        return option
404
405    def lateral_op(self, expression: exp.Lateral) -> str:
406        cross_apply = expression.args.get("cross_apply")
407        if cross_apply is True:
408            return "CROSS APPLY"
409        if cross_apply is False:
410            return "OUTER APPLY"
411
412        # TODO: perhaps we can check if the parent is a Join and transpile it appropriately
413        self.unsupported("LATERAL clause is not supported.")
414        return "LATERAL"
415
416    def splitpart_sql(self, expression: exp.SplitPart) -> str:
417        this = expression.this
418        split_count = len(this.name.split("."))
419        delimiter = expression.args.get("delimiter")
420        part_index = expression.args.get("part_index")
421
422        if (
423            not all(isinstance(arg, exp.Literal) for arg in (this, delimiter, part_index))
424            or (delimiter and delimiter.name != ".")
425            or not part_index
426            or split_count > 4
427        ):
428            self.unsupported(
429                "SPLIT_PART can be transpiled to PARSENAME only for '.' delimiter and literal values"
430            )
431            return ""
432
433        return self.func(
434            "PARSENAME", this, exp.Literal.number(split_count + 1 - part_index.to_py())
435        )
436
437    def _native_dayofweek_sql(self, expression: exp.DayOfWeek) -> str:
438        return self.func("DATEPART", "WEEKDAY", expression.this)
439
440    def extract_sql(self, expression: exp.Extract) -> str:
441        if expression.args.get("uses_session_timezone") and expression.expression.is_type(
442            exp.DType.TIMESTAMPTZ
443        ):
444            self.unsupported(
445                f"Extracting {expression.this.name.upper()} from TIMESTAMPTZ depends on the source session time zone. "
446                "Use AT TIME ZONE on the input to make the time zone explicit."
447            )
448
449        if expression.args.get("zero_based_dow"):
450            # The earliest SQL Server date was a Monday, so the dividend is always positive.
451            days = exp.DateDiff(
452                this=exp.cast(expression.expression, exp.DType.DATE, dialect=self.dialect),
453                expression=exp.Literal.string("00010101"),
454                unit=exp.var("DAY"),
455            )
456            result: exp.Expr = (days + 1) % 7
457        else:
458            part = expression.this
459            name = ""
460            if not expression.args.get("date_part") or isinstance(part, (exp.Var, exp.Literal)):
461                name = part.name.upper()
462            if name != "DOY":
463                return self.func(
464                    "DATEPART", DATE_PART_UNMAPPING.get(name) or part, expression.expression
465                )
466            result = exp.DayOfYear(this=expression.expression.copy())
467
468        if expression.type and not expression.is_type(exp.DType.INT, exp.DType.UNKNOWN):
469            result = exp.cast(result, expression.type, copy=False)
470        elif isinstance(result, exp.Mod):
471            result = exp.paren(result, copy=False)
472        return self.sql(result)
473
474    def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
475        nano = expression.args.get("nano")
476        if nano is not None:
477            nano.pop()
478            self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.")
479
480        if expression.args.get("fractions") is None:
481            expression.set("fractions", exp.Literal.number(0))
482        if expression.args.get("precision") is None:
483            expression.set("precision", exp.Literal.number(0))
484
485        return rename_func("TIMEFROMPARTS")(self, expression)
486
487    def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str:
488        zone = expression.args.get("zone")
489        if zone is not None:
490            zone.pop()
491            self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.")
492
493        nano = expression.args.get("nano")
494        if nano is not None:
495            nano.pop()
496            self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.")
497
498        if expression.args.get("milli") is None:
499            expression.set("milli", exp.Literal.number(0))
500
501        return rename_func("DATETIMEFROMPARTS")(self, expression)
502
503    def setitem_sql(self, expression: exp.SetItem) -> str:
504        this = expression.this
505        if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
506            # T-SQL does not use '=' in SET command, except when the LHS is a variable.
507            return f"{self.sql(this.left)} {self.sql(this.right)}"
508
509        return super().setitem_sql(expression)
510
511    def boolean_sql(self, expression: exp.Boolean) -> str:
512        if type(expression.parent) in BIT_TYPES or isinstance(
513            expression.find_ancestor(exp.Values, exp.Select), exp.Values
514        ):
515            return "1" if expression.this else "0"
516
517        return "(1 = 1)" if expression.this else "(1 = 0)"
518
519    def is_sql(self, expression: exp.Is) -> str:
520        negate = expression.args.get("negate")
521        if isinstance(expression.expression, exp.Boolean):
522            return self.binary(expression, "<>" if negate else "=")
523        return self.binary(expression, "IS NOT" if negate else "IS")
524
525    def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str:
526        sql = self.sql(expression, "this")
527        properties = expression.args.get("properties")
528
529        start = self._identifier_start
530        if (
531            not sql.startswith("#")
532            and not sql.startswith(f"{start}#")
533            and any(
534                isinstance(prop, exp.TemporaryProperty)
535                for prop in (properties.expressions if properties else [])
536            )
537        ):
538            sql = f"{start}#{sql[len(start) :]}" if sql.startswith(start) else f"#{sql}"
539
540        return sql
541
542    def create_sql(self, expression: exp.Create) -> str:
543        kind = expression.kind
544        exists = expression.args.get("exists")
545        expression.set("exists", None)
546
547        like_property = expression.find(exp.LikeProperty)
548        if like_property:
549            ctas_expression = like_property.this
550        else:
551            ctas_expression = expression.expression
552
553        if kind == "VIEW":
554            expression.this.set("catalog", None)
555            with_ = expression.args.get("with_")
556            if ctas_expression and with_:
557                # We've already preprocessed the Create expression to bubble up any nested CTEs,
558                # but CREATE VIEW actually requires the WITH clause to come after it so we need
559                # to amend the AST by moving the CTEs to the CREATE VIEW statement's query.
560                ctas_expression.set("with_", with_.pop())
561        elif (
562            kind == "FUNCTION"
563            and isinstance(ctas_expression, exp.Return)
564            and isinstance(body := ctas_expression.this.unnest(), exp.Query)
565            and (with_ := expression.args.get("with_"))
566        ):
567            # Similar to the VIEW branch, the table-valued functions require the WITH clause
568            # to stay inside the RETURN body, so we move back any CTEs that were bubbled up.
569            body.set("with_", with_.pop())
570
571        table = expression.find(exp.Table)
572
573        # Convert CTAS statement to SELECT .. INTO ..
574        if kind == "TABLE" and ctas_expression:
575            if isinstance(ctas_expression, exp.UNWRAPPED_QUERIES):
576                ctas_expression = ctas_expression.subquery()
577
578            properties = expression.args.get("properties") or exp.Properties()
579            is_temp = any(isinstance(p, exp.TemporaryProperty) for p in properties.expressions)
580
581            select_into = exp.select("*").from_(exp.alias_(ctas_expression, "temp", table=True))
582            select_into.set("into", exp.Into(this=table, temporary=is_temp))
583
584            if like_property:
585                select_into.limit(0, copy=False)
586
587            sql = self.sql(select_into)
588        else:
589            sql = super().create_sql(expression)
590
591        if exists:
592            identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
593            sql_with_ctes = self.prepend_ctes(expression, sql)
594            sql_literal = self.sql(exp.Literal.string(sql_with_ctes))
595            if kind == "SCHEMA":
596                return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = {identifier}) EXEC({sql_literal})"""
597            elif kind == "TABLE":
598                assert table
599                where = exp.and_(
600                    exp.column("TABLE_NAME").eq(table.name),
601                    exp.column("TABLE_SCHEMA").eq(table.db) if table.db else None,
602                    exp.column("TABLE_CATALOG").eq(table.catalog) if table.catalog else None,
603                )
604                return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE {where}) EXEC({sql_literal})"""
605            elif kind == "INDEX":
606                index = self.sql(exp.Literal.string(expression.this.text("this")))
607                return f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql_literal})"""
608        elif expression.args.get("replace"):
609            sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
610
611        return self.prepend_ctes(expression, sql)
612
613    @generator.unsupported_args("unlogged", "expressions")
614    def into_sql(self, expression: exp.Into) -> str:
615        if expression.args.get("temporary"):
616            # If the Into expression has a temporary property, push this down to the Identifier
617            table = expression.find(exp.Table)
618            if table and isinstance(table.this, exp.Identifier):
619                table.this.set("temporary", True)
620
621        return f"{self.seg('INTO')} {self.sql(expression, 'this')}"
622
623    def count_sql(self, expression: exp.Count) -> str:
624        func_name = "COUNT_BIG" if expression.args.get("big_int") else "COUNT"
625        return rename_func(func_name)(self, expression)
626
627    def countif_sql(self, expression: exp.CountIf) -> str:
628        # T-SQL has no COUNT_IF, so count the rows where the predicate holds instead
629        return self.func(
630            "COUNT", exp.If(this=expression.this, true=exp.Literal.number(1), false=exp.null())
631        )
632
633    def datediff_sql(self, expression: exp.DateDiff) -> str:
634        func_name = "DATEDIFF_BIG" if expression.args.get("big_int") else "DATEDIFF"
635        return date_delta_sql(func_name)(self, expression)
636
637    def offset_sql(self, expression: exp.Offset) -> str:
638        return f"{super().offset_sql(expression)} ROWS"
639
640    def version_sql(self, expression: exp.Version) -> str:
641        name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
642        this = f"FOR {name}"
643        expr = expression.expression
644        kind = expression.text("kind")
645        if kind in ("FROM", "BETWEEN"):
646            args = expr.expressions
647            sep = "TO" if kind == "FROM" else "AND"
648            expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
649        else:
650            expr_sql = self.sql(expr)
651
652        expr_sql = f" {expr_sql}" if expr_sql else ""
653        return f"{this} {kind}{expr_sql}"
654
655    def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
656        table = expression.args.get("table")
657        table = f"{table} " if table else ""
658        return f"RETURNS {table}{self.sql(expression, 'this')}"
659
660    def returning_sql(self, expression: exp.Returning) -> str:
661        into = self.sql(expression, "into")
662        into = self.seg(f"INTO {into}") if into else ""
663        return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
664
665    def transaction_sql(self, expression: exp.Transaction) -> str:
666        this = self.sql(expression, "this")
667        this = f" {this}" if this else ""
668        mark = self.sql(expression, "mark")
669        mark = f" WITH MARK {mark}" if mark else ""
670        return f"BEGIN TRANSACTION{this}{mark}"
671
672    def commit_sql(self, expression: exp.Commit) -> str:
673        this = self.sql(expression, "this")
674        this = f" {this}" if this else ""
675        durability = expression.args.get("durability")
676        durability = (
677            f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
678            if durability is not None
679            else ""
680        )
681        return f"COMMIT TRANSACTION{this}{durability}"
682
683    def rollback_sql(self, expression: exp.Rollback) -> str:
684        this = self.sql(expression, "this")
685        this = f" {this}" if this else ""
686        return f"ROLLBACK TRANSACTION{this}"
687
688    def identifier_sql(self, expression: exp.Identifier) -> str:
689        identifier = super().identifier_sql(expression)
690
691        if expression.args.get("global_"):
692            prefix = "##"
693        elif expression.args.get("temporary"):
694            prefix = "#"
695        else:
696            return identifier
697
698        start = self._identifier_start
699        if expression.quoted and identifier.startswith(start):
700            return f"{start}{prefix}{identifier[len(start) :]}"
701
702        return f"{prefix}{identifier}"
703
704    def constraint_sql(self, expression: exp.Constraint) -> str:
705        this = self.sql(expression, "this")
706        expressions = self.expressions(expression, flat=True, sep=" ")
707        return f"CONSTRAINT {this} {expressions}"
708
709    def length_sql(self, expression: exp.Length) -> str:
710        return self._uncast_text(expression, "LEN")
711
712    def right_sql(self, expression: exp.Right) -> str:
713        return self._uncast_text(expression, "RIGHT")
714
715    def left_sql(self, expression: exp.Left) -> str:
716        return self._uncast_text(expression, "LEFT")
717
718    def _uncast_text(self, expression: exp.Expr, name: str) -> str:
719        this = expression.this
720        if isinstance(this, exp.Cast) and this.is_type(exp.DType.TEXT):
721            this_sql = self.sql(this, "this")
722        else:
723            this_sql = self.sql(this)
724        expression_sql = self.sql(expression, "expression")
725        return self.func(name, this_sql, expression_sql if expression_sql else None)
726
727    def partition_sql(self, expression: exp.Partition) -> str:
728        return f"WITH (PARTITIONS({self.expressions(expression, flat=True)}))"
729
730    def alter_sql(self, expression: exp.Alter) -> str:
731        actions = expression.args.get("actions") or []
732        if len(actions) == 1 and isinstance(actions[0], exp.AlterRename):
733            old_name = self.sql(exp.Literal.string(self.sql(expression.this)))
734            new_name = self.sql(exp.Literal.string(actions[0].this.name))
735            return f"EXEC sp_rename {old_name}, {new_name}"
736        return super().alter_sql(expression)
737
738    def drop_sql(self, expression: exp.Drop) -> str:
739        if expression.args["kind"] == "VIEW":
740            for table in expression.args.get("tables") or []:
741                table.set("catalog", None)
742        return super().drop_sql(expression)
743
744    def options_modifier(self, expression: exp.Expr) -> str:
745        options = self.expressions(expression, key="options")
746        return f" OPTION{self.wrap(options)}" if options else ""
747
748    def dpipe_sql(self, expression: exp.DPipe) -> str:
749        return self.sql(reduce(lambda x, y: exp.Add(this=x, expression=y), expression.flatten()))
750
751    def isascii_sql(self, expression: exp.IsAscii) -> str:
752        return f"(PATINDEX(CONVERT(VARCHAR(MAX), 0x255b5e002d7f5d25) COLLATE Latin1_General_BIN, {self.sql(expression.this)}) = 0)"
753
754    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
755        this = super().columndef_sql(expression, sep)
756        default = self.sql(expression, "default")
757        default = f" = {default}" if default else ""
758        output = self.sql(expression, "output")
759        output = f" {output}" if output else ""
760        return f"{this}{default}{output}"
761
762    def coalesce_sql(self, expression: exp.Coalesce) -> str:
763        func_name = "ISNULL" if expression.args.get("is_null") else "COALESCE"
764        return rename_func(func_name)(self, expression)
765
766    def storedprocedure_sql(self, expression: exp.StoredProcedure) -> str:
767        this = self.sql(expression, "this")
768        expressions = self.expressions(expression)
769        expressions = (
770            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
771        )
772        return f"{this}{expressions}" if expressions.strip() != "" else this
773
774    def ifblock_sql(self, expression: exp.IfBlock) -> str:
775        this = self.sql(expression, "this")
776        true = self.sql(expression, "true")
777        true = f" {true}" if true else " "
778        false = self.sql(expression, "false")
779        false = f"; ELSE BEGIN {false}" if false else ""
780        return f"IF {this} BEGIN{true}{false}"
781
782    def whileblock_sql(self, expression: exp.WhileBlock) -> str:
783        this = self.sql(expression, "this")
784        body = self.sql(expression, "body")
785        body = f" {body}" if body else " "
786        return f"WHILE {this} BEGIN{body}"
787
788    def execute_sql(self, expression: exp.Execute) -> str:
789        this = self.sql(expression, "this")
790        expressions = self.expressions(expression)
791        expressions = f" {expressions}" if expressions else ""
792        return_status = self.sql(expression, "return_status")
793        return_status = f"{return_status} = " if return_status else ""
794        return f"EXECUTE {return_status}{this}{expressions}"
795
796    def executesql_sql(self, expression: exp.ExecuteSql) -> str:
797        return self.execute_sql(expression)

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: Always quote except for specials cases. '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
SELECT_KINDS = ()
TRY_SUPPORTED = False
SUPPORTS_UESCAPE = False
SUPPORTS_DECODE_CASE = False
SUPPORTS_MULTI_ARG_CHR = False
AFTER_HAVING_MODIFIER_TRANSFORMS = {'windows': <function <lambda>>, 'qualify': <function <lambda>>}
LIMIT_IS_TOP = True
SET_OP_LIMITS = True
QUERY_HINTS = False
RETURNING_END = False
NVL2_SUPPORTED = False
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
ALTER_TABLE_ADD_COLUMNS_WRAPPED = False
LIMIT_FETCH = 'FETCH'
COMPUTED_COLUMN_WITH_TYPE = False
CTE_RECURSIVE_KEYWORD_REQUIRED = False
ENSURE_BOOLS = True
NULL_ORDERING_SUPPORTED: bool | None = None
SUPPORTS_SINGLE_ARG_CONCAT = False
TABLESAMPLE_SEED_KEYWORD = 'REPEATABLE'
SUPPORTS_SELECT_INTO = True
JSON_PATH_BRACKETED_KEY_SUPPORTED = False
SUPPORTS_TO_NUMBER = False
COPY_PARAMS_EQ_REQUIRED = True
PARSE_JSON_NAME: str | None = None
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
ALTER_SET_WRAPPED = True
ALTER_SET_TYPE = ''
SUPPORTS_ALTER_COLUMN_NULLABILITY = True
TYPE_MAPPING = {<DType.DATETIME2: 'DATETIME2'>: 'DATETIME2', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <DType.LONGTEXT: 'LONGTEXT'>: 'TEXT', <DType.TINYTEXT: 'TINYTEXT'>: 'TEXT', <DType.BLOB: 'BLOB'>: 'VARBINARY', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <DType.LONGBLOB: 'LONGBLOB'>: 'BLOB', <DType.TINYBLOB: 'TINYBLOB'>: 'BLOB', <DType.INET: 'INET'>: 'INET', <DType.ROWVERSION: 'ROWVERSION'>: 'ROWVERSION', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'SMALLDATETIME', <DType.BOOLEAN: 'BOOLEAN'>: 'BIT', <DType.DECIMAL: 'DECIMAL'>: 'NUMERIC', <DType.DOUBLE: 'DOUBLE'>: 'FLOAT', <DType.INT: 'INT'>: 'INTEGER', <DType.TEXT: 'TEXT'>: 'VARCHAR(MAX)', <DType.TIMESTAMP: 'TIMESTAMP'>: 'DATETIME2', <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>: 'DATETIME2', <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'DATETIMEOFFSET', <DType.TINYINT: 'TINYINT'>: 'SMALLINT', <DType.UTINYINT: 'UTINYINT'>: 'TINYINT', <DType.VARIANT: 'VARIANT'>: 'SQL_VARIANT', <DType.UUID: 'UUID'>: 'UNIQUEIDENTIFIER'}
TRANSFORMS = {<class 'sqlglot.expressions.query.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.core.Adjacent'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainedBy'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.AssumeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.BinaryColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Ceil'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentCatalog'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.SessionUser'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApiProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.EndStatement'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HybridProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.datatypes.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAnyTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAllTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsTopKey'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBPathExists'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.NetFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsLeft'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsRight'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.PositionalColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InvisibleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ZeroFillColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.SafeFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.constraints.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.TriggerExecute'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcDate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTime'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTimestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Variadic'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ForceProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.aggregate.AnyValue'>: <function any_value_to_max_sql>, <class 'sqlglot.expressions.math.Atan2'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArrayToString'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.constraints.AutoIncrementColumnConstraint'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.string.Chr'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DateAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.query.CTE'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.temporal.CurrentDate'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.CurrentTimestamp'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.CurrentTimestampLTZ'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.temporal.Day'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.core.Filter'>: <function no_filter_sql>, <class 'sqlglot.expressions.constraints.GeneratedAsIdentityColumnConstraint'>: <function generatedasidentitycolumnconstraint_sql>, <class 'sqlglot.expressions.aggregate.GroupConcat'>: <function _string_agg_sql>, <class 'sqlglot.expressions.functions.If'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.json.JSONExtract'>: <function _json_extract_sql>, <class 'sqlglot.expressions.json.JSONExtractScalar'>: <function _json_extract_sql>, <class 'sqlglot.expressions.temporal.LastDay'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.math.Ln'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.string.MD5'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.Min'>: <function min_or_least>, <class 'sqlglot.expressions.temporal.Month'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.string.NumberToStr'>: <function _format_sql>, <class 'sqlglot.expressions.string.Repeat'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.CurrentSchema'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.aggregate.Stddev'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.StrPosition'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.query.Subquery'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.SHA'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.string.SHA1Digest'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.string.SHA2'>: <function _sha2_sql>, <class 'sqlglot.expressions.string.SHA2Digest'>: <function _sha2_sql>, <class 'sqlglot.expressions.temporal.TimeStrToTime'>: <function _timestrtotime_sql>, <class 'sqlglot.expressions.temporal.TimeToStr'>: <function _format_sql>, <class 'sqlglot.expressions.temporal.TimestampAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.string.Trim'>: <function trim_sql>, <class 'sqlglot.expressions.temporal.TsOrDsAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TsOrDsDiff'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TimestampTrunc'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.math.Trunc'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.functions.Uuid'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Year'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.temporal.DateFromParts'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DayOfYear'>: <function TSQLGenerator.<lambda>>}
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.properties.AggregateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AlgorithmProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApiProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.AutoIncrementProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BackupProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BlockCompressionProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ChecksumProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CollateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.query.Cluster'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusteredByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusterProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistributedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DuplicateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DataBlocksizeProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DataDeletionProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DefinerProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DictRange'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DistKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EncodeProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.EngineProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.FallbackProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.FreespaceProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.HeapProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.HybridProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IncludeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InteractiveProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.IsolatedLoadingProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.JournalProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LikeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LocationProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockingProperty'>: <PropertiesLocation.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.properties.LogProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MergeBlockRatioProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.ModuleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OnProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OptionsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.query.Order'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.PartitionedOfProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PhysicalProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.constraints.PrimaryKey'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Property'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.RefreshTriggerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RollupProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowFormatProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatDelimitedProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatSerdeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SampleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SchemaCommentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SecureProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SerdeProperties'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.Set'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SetProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SharingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.SequenceProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.TriggerProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.SortKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageHandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.StrictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Tags'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.TableSpaceProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.TransientProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.MergeTreeTTL'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.UsingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithDataProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSystemVersioningProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ForceProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>}
def scope_resolution(self, rhs: str, scope_name: str) -> str:
292    def scope_resolution(self, rhs: str, scope_name: str) -> str:
293        return f"{scope_name}::{rhs}"
def datetrunc_sql(self, expression: sqlglot.expressions.temporal.DateTrunc) -> str:
297    def datetrunc_sql(self, expression: exp.DateTrunc) -> str:
298        self._warn_unsupported_arg(expression, "zone")
299        self._warn_unsupported_arg(expression, "century_from_zero")
300        unit_expr = expression.unit
301        if isinstance(unit_expr, exp.WeekStart):
302            unit: exp.Expr | None = exp.var(
303                "ISO_WEEK" if unit_expr.name.upper() == "MONDAY" else self.weekstart_name(unit_expr)
304            )
305        else:
306            if unit_expr.is_string and unit_expr.name.upper() in ("WEEK_OF_MONTH", "WEEK_OF_YEAR"):
307                self.unsupported(f"Unexpected interval unit: {unit_expr.name}")
308            unit = unit_to_var(expression)
309            if isinstance(unit, exp.Var) and unit.name.upper() == "ISOWEEK":
310                unit = exp.var("ISO_WEEK")
311        return self.func("DATETRUNC", unit, expression.this)
def select_sql(self, expression: sqlglot.expressions.query.Select) -> str:
313    def select_sql(self, expression: exp.Select) -> str:
314        self._prepare_limit_offset(expression)
315
316        # Handles transpiling a query like the following to T-SQL:
317        #   SELECT 1 AS x ORDER BY x NULLS FIRST FETCH FIRST 1 ROWS ONLY UNION ALL SELECT 2 AS x
318        if isinstance(expression.parent, exp.SetOperation) and isinstance(
319            expression.args.get("limit"), exp.Fetch
320        ):
321            return self.sql(
322                exp.select("*").from_(expression.subquery("_l_0", copy=False), copy=False)
323            )
324
325        return super().select_sql(expression)
def set_operations(self, expression: sqlglot.expressions.query.SetOperation) -> str:
327    def set_operations(self, expression: exp.SetOperation) -> str:
328        limit = expression.args.get("limit")
329        offset = expression.args.get("offset")
330        order = expression.args.get("order")
331
332        # Set operations cannot order by the CASE used to emulate null ordering,
333        # or by expressions that aren't in their select list.
334        wrap_order = False
335        if order:
336            selects = {select.unalias().unnest() for select in expression.selects}
337            for ordered in order.expressions:
338                this = ordered.this.unnest()
339                if this.is_int:
340                    continue
341
342                desc = ordered.args.get("desc")
343                nulls_first = ordered.args.get("nulls_first")
344
345                emulate_null_ordering = (desc and nulls_first) or (not desc and not nulls_first)
346                if emulate_null_ordering or (
347                    not isinstance(this, exp.Column) and this not in selects
348                ):
349                    wrap_order = True
350                    break
351
352        if (
353            wrap_order
354            or (isinstance(limit, exp.Limit) and not offset)
355            or (not order and (offset or isinstance(limit, exp.Fetch)))
356        ):
357            select = self._move_ctes_to_top_level(
358                exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
359            )
360            for arg in SET_OP_MODIFIERS:
361                value = expression.args.get(arg)
362                if value:
363                    expression.set(arg, None)
364                    select.set(arg, value)
365
366            return self.sql(select)
367
368        self._prepare_limit_offset(expression)
369        return super().set_operations(expression)
def convert_sql(self, expression: sqlglot.expressions.functions.Convert) -> str:
393    def convert_sql(self, expression: exp.Convert) -> str:
394        name = "TRY_CONVERT" if expression.args.get("safe") else "CONVERT"
395        return self.func(name, expression.this, expression.expression, expression.args.get("style"))
def queryoption_sql(self, expression: sqlglot.expressions.query.QueryOption) -> str:
397    def queryoption_sql(self, expression: exp.QueryOption) -> str:
398        option = self.sql(expression, "this")
399        value = self.sql(expression, "expression")
400        if value:
401            optional_equal_sign = "= " if option in OPTIONS_THAT_REQUIRE_EQUAL else ""
402            return f"{option} {optional_equal_sign}{value}"
403        return option
def lateral_op(self, expression: sqlglot.expressions.query.Lateral) -> str:
405    def lateral_op(self, expression: exp.Lateral) -> str:
406        cross_apply = expression.args.get("cross_apply")
407        if cross_apply is True:
408            return "CROSS APPLY"
409        if cross_apply is False:
410            return "OUTER APPLY"
411
412        # TODO: perhaps we can check if the parent is a Join and transpile it appropriately
413        self.unsupported("LATERAL clause is not supported.")
414        return "LATERAL"
def splitpart_sql(self, expression: sqlglot.expressions.string.SplitPart) -> str:
416    def splitpart_sql(self, expression: exp.SplitPart) -> str:
417        this = expression.this
418        split_count = len(this.name.split("."))
419        delimiter = expression.args.get("delimiter")
420        part_index = expression.args.get("part_index")
421
422        if (
423            not all(isinstance(arg, exp.Literal) for arg in (this, delimiter, part_index))
424            or (delimiter and delimiter.name != ".")
425            or not part_index
426            or split_count > 4
427        ):
428            self.unsupported(
429                "SPLIT_PART can be transpiled to PARSENAME only for '.' delimiter and literal values"
430            )
431            return ""
432
433        return self.func(
434            "PARSENAME", this, exp.Literal.number(split_count + 1 - part_index.to_py())
435        )
def extract_sql(self, expression: sqlglot.expressions.temporal.Extract) -> str:
440    def extract_sql(self, expression: exp.Extract) -> str:
441        if expression.args.get("uses_session_timezone") and expression.expression.is_type(
442            exp.DType.TIMESTAMPTZ
443        ):
444            self.unsupported(
445                f"Extracting {expression.this.name.upper()} from TIMESTAMPTZ depends on the source session time zone. "
446                "Use AT TIME ZONE on the input to make the time zone explicit."
447            )
448
449        if expression.args.get("zero_based_dow"):
450            # The earliest SQL Server date was a Monday, so the dividend is always positive.
451            days = exp.DateDiff(
452                this=exp.cast(expression.expression, exp.DType.DATE, dialect=self.dialect),
453                expression=exp.Literal.string("00010101"),
454                unit=exp.var("DAY"),
455            )
456            result: exp.Expr = (days + 1) % 7
457        else:
458            part = expression.this
459            name = ""
460            if not expression.args.get("date_part") or isinstance(part, (exp.Var, exp.Literal)):
461                name = part.name.upper()
462            if name != "DOY":
463                return self.func(
464                    "DATEPART", DATE_PART_UNMAPPING.get(name) or part, expression.expression
465                )
466            result = exp.DayOfYear(this=expression.expression.copy())
467
468        if expression.type and not expression.is_type(exp.DType.INT, exp.DType.UNKNOWN):
469            result = exp.cast(result, expression.type, copy=False)
470        elif isinstance(result, exp.Mod):
471            result = exp.paren(result, copy=False)
472        return self.sql(result)
def timefromparts_sql(self, expression: sqlglot.expressions.temporal.TimeFromParts) -> str:
474    def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
475        nano = expression.args.get("nano")
476        if nano is not None:
477            nano.pop()
478            self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.")
479
480        if expression.args.get("fractions") is None:
481            expression.set("fractions", exp.Literal.number(0))
482        if expression.args.get("precision") is None:
483            expression.set("precision", exp.Literal.number(0))
484
485        return rename_func("TIMEFROMPARTS")(self, expression)
def timestampfromparts_sql(self, expression: sqlglot.expressions.temporal.TimestampFromParts) -> str:
487    def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str:
488        zone = expression.args.get("zone")
489        if zone is not None:
490            zone.pop()
491            self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.")
492
493        nano = expression.args.get("nano")
494        if nano is not None:
495            nano.pop()
496            self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.")
497
498        if expression.args.get("milli") is None:
499            expression.set("milli", exp.Literal.number(0))
500
501        return rename_func("DATETIMEFROMPARTS")(self, expression)
def setitem_sql(self, expression: sqlglot.expressions.ddl.SetItem) -> str:
503    def setitem_sql(self, expression: exp.SetItem) -> str:
504        this = expression.this
505        if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
506            # T-SQL does not use '=' in SET command, except when the LHS is a variable.
507            return f"{self.sql(this.left)} {self.sql(this.right)}"
508
509        return super().setitem_sql(expression)
def boolean_sql(self, expression: sqlglot.expressions.core.Boolean) -> str:
511    def boolean_sql(self, expression: exp.Boolean) -> str:
512        if type(expression.parent) in BIT_TYPES or isinstance(
513            expression.find_ancestor(exp.Values, exp.Select), exp.Values
514        ):
515            return "1" if expression.this else "0"
516
517        return "(1 = 1)" if expression.this else "(1 = 0)"
def is_sql(self, expression: sqlglot.expressions.core.Is) -> str:
519    def is_sql(self, expression: exp.Is) -> str:
520        negate = expression.args.get("negate")
521        if isinstance(expression.expression, exp.Boolean):
522            return self.binary(expression, "<>" if negate else "=")
523        return self.binary(expression, "IS NOT" if negate else "IS")
def createable_sql( self, expression: sqlglot.expressions.ddl.Create, locations: collections.defaultdict) -> str:
525    def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str:
526        sql = self.sql(expression, "this")
527        properties = expression.args.get("properties")
528
529        start = self._identifier_start
530        if (
531            not sql.startswith("#")
532            and not sql.startswith(f"{start}#")
533            and any(
534                isinstance(prop, exp.TemporaryProperty)
535                for prop in (properties.expressions if properties else [])
536            )
537        ):
538            sql = f"{start}#{sql[len(start) :]}" if sql.startswith(start) else f"#{sql}"
539
540        return sql
def create_sql(self, expression: sqlglot.expressions.ddl.Create) -> str:
542    def create_sql(self, expression: exp.Create) -> str:
543        kind = expression.kind
544        exists = expression.args.get("exists")
545        expression.set("exists", None)
546
547        like_property = expression.find(exp.LikeProperty)
548        if like_property:
549            ctas_expression = like_property.this
550        else:
551            ctas_expression = expression.expression
552
553        if kind == "VIEW":
554            expression.this.set("catalog", None)
555            with_ = expression.args.get("with_")
556            if ctas_expression and with_:
557                # We've already preprocessed the Create expression to bubble up any nested CTEs,
558                # but CREATE VIEW actually requires the WITH clause to come after it so we need
559                # to amend the AST by moving the CTEs to the CREATE VIEW statement's query.
560                ctas_expression.set("with_", with_.pop())
561        elif (
562            kind == "FUNCTION"
563            and isinstance(ctas_expression, exp.Return)
564            and isinstance(body := ctas_expression.this.unnest(), exp.Query)
565            and (with_ := expression.args.get("with_"))
566        ):
567            # Similar to the VIEW branch, the table-valued functions require the WITH clause
568            # to stay inside the RETURN body, so we move back any CTEs that were bubbled up.
569            body.set("with_", with_.pop())
570
571        table = expression.find(exp.Table)
572
573        # Convert CTAS statement to SELECT .. INTO ..
574        if kind == "TABLE" and ctas_expression:
575            if isinstance(ctas_expression, exp.UNWRAPPED_QUERIES):
576                ctas_expression = ctas_expression.subquery()
577
578            properties = expression.args.get("properties") or exp.Properties()
579            is_temp = any(isinstance(p, exp.TemporaryProperty) for p in properties.expressions)
580
581            select_into = exp.select("*").from_(exp.alias_(ctas_expression, "temp", table=True))
582            select_into.set("into", exp.Into(this=table, temporary=is_temp))
583
584            if like_property:
585                select_into.limit(0, copy=False)
586
587            sql = self.sql(select_into)
588        else:
589            sql = super().create_sql(expression)
590
591        if exists:
592            identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
593            sql_with_ctes = self.prepend_ctes(expression, sql)
594            sql_literal = self.sql(exp.Literal.string(sql_with_ctes))
595            if kind == "SCHEMA":
596                return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = {identifier}) EXEC({sql_literal})"""
597            elif kind == "TABLE":
598                assert table
599                where = exp.and_(
600                    exp.column("TABLE_NAME").eq(table.name),
601                    exp.column("TABLE_SCHEMA").eq(table.db) if table.db else None,
602                    exp.column("TABLE_CATALOG").eq(table.catalog) if table.catalog else None,
603                )
604                return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE {where}) EXEC({sql_literal})"""
605            elif kind == "INDEX":
606                index = self.sql(exp.Literal.string(expression.this.text("this")))
607                return f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql_literal})"""
608        elif expression.args.get("replace"):
609            sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
610
611        return self.prepend_ctes(expression, sql)
@generator.unsupported_args('unlogged', 'expressions')
def into_sql(self, expression: sqlglot.expressions.query.Into) -> str:
613    @generator.unsupported_args("unlogged", "expressions")
614    def into_sql(self, expression: exp.Into) -> str:
615        if expression.args.get("temporary"):
616            # If the Into expression has a temporary property, push this down to the Identifier
617            table = expression.find(exp.Table)
618            if table and isinstance(table.this, exp.Identifier):
619                table.this.set("temporary", True)
620
621        return f"{self.seg('INTO')} {self.sql(expression, 'this')}"
def count_sql(self, expression: sqlglot.expressions.aggregate.Count) -> str:
623    def count_sql(self, expression: exp.Count) -> str:
624        func_name = "COUNT_BIG" if expression.args.get("big_int") else "COUNT"
625        return rename_func(func_name)(self, expression)
def countif_sql(self, expression: sqlglot.expressions.aggregate.CountIf) -> str:
627    def countif_sql(self, expression: exp.CountIf) -> str:
628        # T-SQL has no COUNT_IF, so count the rows where the predicate holds instead
629        return self.func(
630            "COUNT", exp.If(this=expression.this, true=exp.Literal.number(1), false=exp.null())
631        )
def datediff_sql(self, expression: sqlglot.expressions.temporal.DateDiff) -> str:
633    def datediff_sql(self, expression: exp.DateDiff) -> str:
634        func_name = "DATEDIFF_BIG" if expression.args.get("big_int") else "DATEDIFF"
635        return date_delta_sql(func_name)(self, expression)
def offset_sql(self, expression: sqlglot.expressions.query.Offset) -> str:
637    def offset_sql(self, expression: exp.Offset) -> str:
638        return f"{super().offset_sql(expression)} ROWS"
def version_sql(self, expression: sqlglot.expressions.query.Version) -> str:
640    def version_sql(self, expression: exp.Version) -> str:
641        name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
642        this = f"FOR {name}"
643        expr = expression.expression
644        kind = expression.text("kind")
645        if kind in ("FROM", "BETWEEN"):
646            args = expr.expressions
647            sep = "TO" if kind == "FROM" else "AND"
648            expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
649        else:
650            expr_sql = self.sql(expr)
651
652        expr_sql = f" {expr_sql}" if expr_sql else ""
653        return f"{this} {kind}{expr_sql}"
def returnsproperty_sql(self, expression: sqlglot.expressions.properties.ReturnsProperty) -> str:
655    def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
656        table = expression.args.get("table")
657        table = f"{table} " if table else ""
658        return f"RETURNS {table}{self.sql(expression, 'this')}"
def returning_sql(self, expression: sqlglot.expressions.dml.Returning) -> str:
660    def returning_sql(self, expression: exp.Returning) -> str:
661        into = self.sql(expression, "into")
662        into = self.seg(f"INTO {into}") if into else ""
663        return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
def transaction_sql(self, expression: sqlglot.expressions.ddl.Transaction) -> str:
665    def transaction_sql(self, expression: exp.Transaction) -> str:
666        this = self.sql(expression, "this")
667        this = f" {this}" if this else ""
668        mark = self.sql(expression, "mark")
669        mark = f" WITH MARK {mark}" if mark else ""
670        return f"BEGIN TRANSACTION{this}{mark}"
def commit_sql(self, expression: sqlglot.expressions.ddl.Commit) -> str:
672    def commit_sql(self, expression: exp.Commit) -> str:
673        this = self.sql(expression, "this")
674        this = f" {this}" if this else ""
675        durability = expression.args.get("durability")
676        durability = (
677            f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
678            if durability is not None
679            else ""
680        )
681        return f"COMMIT TRANSACTION{this}{durability}"
def rollback_sql(self, expression: sqlglot.expressions.ddl.Rollback) -> str:
683    def rollback_sql(self, expression: exp.Rollback) -> str:
684        this = self.sql(expression, "this")
685        this = f" {this}" if this else ""
686        return f"ROLLBACK TRANSACTION{this}"
def identifier_sql(self, expression: sqlglot.expressions.core.Identifier) -> str:
688    def identifier_sql(self, expression: exp.Identifier) -> str:
689        identifier = super().identifier_sql(expression)
690
691        if expression.args.get("global_"):
692            prefix = "##"
693        elif expression.args.get("temporary"):
694            prefix = "#"
695        else:
696            return identifier
697
698        start = self._identifier_start
699        if expression.quoted and identifier.startswith(start):
700            return f"{start}{prefix}{identifier[len(start) :]}"
701
702        return f"{prefix}{identifier}"
def constraint_sql(self, expression: sqlglot.expressions.constraints.Constraint) -> str:
704    def constraint_sql(self, expression: exp.Constraint) -> str:
705        this = self.sql(expression, "this")
706        expressions = self.expressions(expression, flat=True, sep=" ")
707        return f"CONSTRAINT {this} {expressions}"
def length_sql(self, expression: sqlglot.expressions.string.Length) -> str:
709    def length_sql(self, expression: exp.Length) -> str:
710        return self._uncast_text(expression, "LEN")
def right_sql(self, expression: sqlglot.expressions.string.Right) -> str:
712    def right_sql(self, expression: exp.Right) -> str:
713        return self._uncast_text(expression, "RIGHT")
def left_sql(self, expression: sqlglot.expressions.string.Left) -> str:
715    def left_sql(self, expression: exp.Left) -> str:
716        return self._uncast_text(expression, "LEFT")
def partition_sql(self, expression: sqlglot.expressions.query.Partition) -> str:
727    def partition_sql(self, expression: exp.Partition) -> str:
728        return f"WITH (PARTITIONS({self.expressions(expression, flat=True)}))"
def alter_sql(self, expression: sqlglot.expressions.ddl.Alter) -> str:
730    def alter_sql(self, expression: exp.Alter) -> str:
731        actions = expression.args.get("actions") or []
732        if len(actions) == 1 and isinstance(actions[0], exp.AlterRename):
733            old_name = self.sql(exp.Literal.string(self.sql(expression.this)))
734            new_name = self.sql(exp.Literal.string(actions[0].this.name))
735            return f"EXEC sp_rename {old_name}, {new_name}"
736        return super().alter_sql(expression)
def drop_sql(self, expression: sqlglot.expressions.ddl.Drop) -> str:
738    def drop_sql(self, expression: exp.Drop) -> str:
739        if expression.args["kind"] == "VIEW":
740            for table in expression.args.get("tables") or []:
741                table.set("catalog", None)
742        return super().drop_sql(expression)
def options_modifier(self, expression: sqlglot.expressions.core.Expr) -> str:
744    def options_modifier(self, expression: exp.Expr) -> str:
745        options = self.expressions(expression, key="options")
746        return f" OPTION{self.wrap(options)}" if options else ""
def dpipe_sql(self, expression: sqlglot.expressions.core.DPipe) -> str:
748    def dpipe_sql(self, expression: exp.DPipe) -> str:
749        return self.sql(reduce(lambda x, y: exp.Add(this=x, expression=y), expression.flatten()))
def isascii_sql(self, expression: sqlglot.expressions.string.IsAscii) -> str:
751    def isascii_sql(self, expression: exp.IsAscii) -> str:
752        return f"(PATINDEX(CONVERT(VARCHAR(MAX), 0x255b5e002d7f5d25) COLLATE Latin1_General_BIN, {self.sql(expression.this)}) = 0)"
def columndef_sql( self, expression: sqlglot.expressions.query.ColumnDef, sep: str = ' ') -> str:
754    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
755        this = super().columndef_sql(expression, sep)
756        default = self.sql(expression, "default")
757        default = f" = {default}" if default else ""
758        output = self.sql(expression, "output")
759        output = f" {output}" if output else ""
760        return f"{this}{default}{output}"
def coalesce_sql(self, expression: sqlglot.expressions.functions.Coalesce) -> str:
762    def coalesce_sql(self, expression: exp.Coalesce) -> str:
763        func_name = "ISNULL" if expression.args.get("is_null") else "COALESCE"
764        return rename_func(func_name)(self, expression)
def storedprocedure_sql(self, expression: sqlglot.expressions.query.StoredProcedure) -> str:
766    def storedprocedure_sql(self, expression: exp.StoredProcedure) -> str:
767        this = self.sql(expression, "this")
768        expressions = self.expressions(expression)
769        expressions = (
770            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
771        )
772        return f"{this}{expressions}" if expressions.strip() != "" else this
def ifblock_sql(self, expression: sqlglot.expressions.query.IfBlock) -> str:
774    def ifblock_sql(self, expression: exp.IfBlock) -> str:
775        this = self.sql(expression, "this")
776        true = self.sql(expression, "true")
777        true = f" {true}" if true else " "
778        false = self.sql(expression, "false")
779        false = f"; ELSE BEGIN {false}" if false else ""
780        return f"IF {this} BEGIN{true}{false}"
def whileblock_sql(self, expression: sqlglot.expressions.query.WhileBlock) -> str:
782    def whileblock_sql(self, expression: exp.WhileBlock) -> str:
783        this = self.sql(expression, "this")
784        body = self.sql(expression, "body")
785        body = f" {body}" if body else " "
786        return f"WHILE {this} BEGIN{body}"
def execute_sql(self, expression: sqlglot.expressions.ddl.Execute) -> str:
788    def execute_sql(self, expression: exp.Execute) -> str:
789        this = self.sql(expression, "this")
790        expressions = self.expressions(expression)
791        expressions = f" {expressions}" if expressions else ""
792        return_status = self.sql(expression, "return_status")
793        return_status = f"{return_status} = " if return_status else ""
794        return f"EXECUTE {return_status}{this}{expressions}"
def executesql_sql(self, expression: sqlglot.expressions.ddl.ExecuteSql) -> str:
796    def executesql_sql(self, expression: exp.ExecuteSql) -> str:
797        return self.execute_sql(expression)
Inherited Members
sqlglot.generator.Generator
Generator
WINDOW_FUNCS_WITH_NULL_ORDERING
WINDOW_FUNCS_REQUIRING_ORDER
IGNORE_NULLS_IN_FUNC
IGNORE_NULLS_BEFORE_ORDER
LOCKING_READS_SUPPORTED
WRAP_DERIVED_VALUES
CREATE_FUNCTION_RETURN_AS
MATCHED_BY_SOURCE
SUPPORTS_MERGE_WHERE
MERGE_SCHEMA_EVOLUTION_MIN_VERSION
MERGE_ALL_BY_NAME
SINGLE_STRING_INTERVAL
INTERVAL_ALLOWS_PLURAL_FORM
AUTO_REFRESH_BARE_INTERVALS
LIMIT_ONLY_LITERALS
RENAME_TABLE_WITH_DB
GROUPINGS_SEP
SUPPORTS_GROUPING_SETS_AS_SUFFIX
INDEX_ON
INOUT_SEPARATOR
JOIN_HINTS
DIRECTED_JOINS
SUPPORTS_NEAREST_JOIN
SUPPORTS_MATCH_CONDITION
MATCH_CONDITION_IN_ON
TABLE_HINTS
QUERY_HINT_SEP
IS_BOOL_ALLOWED
CAST_TO_INT_ROUNDS
SAFE_INT_DIVISION
INT_DIV_OPERATOR
DUPLICATE_KEY_UPDATE_WITH_SET
EXTRACT_ALLOWS_QUOTES
TZ_TO_WITH_TIME_ZONE
VALUES_AS_TABLE
UNNEST_WITH_ORDINALITY
SEMI_ANTI_JOIN_WITH_SIDE
SUPPORTS_TABLE_COPY
TABLESAMPLE_REQUIRES_PARENS
TABLESAMPLE_SIZE_IS_ROWS
TABLESAMPLE_KEYWORDS
TABLESAMPLE_WITH_METHOD
HISTORICAL_DATA_POST_ALIAS
COLLATE_IS_FUNC
DATA_TYPE_SPECIFIERS_ALLOWED
LAST_DAY_SUPPORTS_DATE_PART
SUPPORTS_TABLE_ALIAS_COLUMNS
SUPPORTS_NAMED_CTE_COLUMNS
UNPIVOT_ALIASES_ARE_IDENTIFIERS
PIVOT_ALIAS_WITH_AS
JSON_KEY_VALUE_PAIR_SEP
INSERT_OVERWRITE
SUPPORTS_OPTIMIZE
SUPPORTS_EXECUTE_IMMEDIATE
SUPPORTS_UNLOGGED_TABLES
SUPPORTS_CREATE_TABLE_LIKE
SUPPORTS_MODIFY_COLUMN
SUPPORTS_CHANGE_COLUMN
SUPPORTS_ALTER_COLUMN_IF_EXISTS
LIKE_PROPERTY_INSIDE_SCHEMA
MULTI_ARG_DISTINCT
JSON_TYPE_REQUIRED_FOR_EXTRACTION
SUPPORTS_NESTED_JSON_SELECT
JSON_PATH_SINGLE_QUOTE_ESCAPE
JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
CAN_IMPLEMENT_ARRAY_ANY
SUPPORTS_WINDOW_EXCLUDE
SET_OP_MODIFIERS
SET_OP_PARENTHESIZED_OPERANDS
COPY_PARAMS_ARE_WRAPPED
COPY_HAS_INTO_KEYWORD
UNICODE_SUBSTITUTE
STAR_EXCEPT
HEX_FUNC
BYTE_STRING_FUNCTION
WITH_PROPERTIES_PREFIX
QUOTE_JSON_PATH
PAD_FILL_PATTERN_IS_REQUIRED
SUPPORTS_EXPLODING_PROJECTIONS
ARRAY_CONCAT_IS_VAR_LEN
SUPPORTS_CONVERT_TIMEZONE
SUPPORTS_MEDIAN
SUPPORTS_UNIX_SECONDS
NORMALIZE_EXTRACT_DATE_PARTS
ARRAY_SIZE_NAME
DAYOFWEEK_NAME
DAYOFWEEK_ZERO_BASED
VARIANCE_NAME
VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE
ARRAY_SIZE_DIM_REQUIRED
SUPPORTS_BETWEEN_FLAGS
SUPPORTS_LIKE_QUANTIFIERS
MATCH_AGAINST_TABLE_PREFIX
SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD
DECLARE_DEFAULT_ASSIGNMENT
UPDATE_STATEMENT_SUPPORTS_FROM
STAR_EXCLUDE_REQUIRES_DERIVED_TABLE
SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY
UNSUPPORTED_TYPES
TYPE_PARAM_SETTINGS
TIME_PART_SINGULARS
TOKEN_MAPPING
STRUCT_DELIMITER
PARAMETER_TOKEN
NAMED_PLACEHOLDER_TOKEN
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
RESERVED_KEYWORDS
WITH_SEPARATED_COMMENTS
EXCLUDE_COMMENTS
UNWRAPPED_INTERVAL_VALUES
PARAMETERIZABLE_TEXT_TYPES
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS
MOD_OPERATOR
BARE_OPERATORS
MOD_PAREN_PARENT_TYPES
ALTER_PARTITION_OPTIONS
SAFE_JSON_PATH_KEY_RE
SENTINEL_LINE_BREAK
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages
generate
preprocess
unsupported
sep
seg
sanitize_comment
maybe_comment
wrap
no_identify
normalize_func
indent
sql
uncache_sql
cache_sql
characterset_sql
column_parts
column_sql
pseudocolumn_sql
columnposition_sql
columnconstraint_sql
computedcolumnconstraint_sql
autoincrementcolumnconstraint_sql
compresscolumnconstraint_sql
generatedasidentitycolumnconstraint_sql
generatedasrowcolumnconstraint_sql
periodforsystemtimeconstraint_sql
notnullcolumnconstraint_sql
primarykeycolumnconstraint_sql
uniquecolumnconstraint_sql
inoutcolumnconstraint_sql
sequenceproperties_sql
triggerproperties_sql
triggerreferencing_sql
triggerevent_sql
clone_sql
describe_sql
heredoc_sql
prepend_ctes
with_sql
cte_sql
tablealias_sql
bitstring_sql
hexstring_sql
bytestring_sql
unicodestring_sql
rawstring_sql
datatypeparam_sql
datatype_param_bound_limiter
datatype_sql
directory_sql
delete_sql
set_operation
fetch_sql
limitoptions_sql
filter_sql
per_sql
hint_sql
indexparameters_sql
index_sql
dynamicidentifier_sql
hex_sql
lowerhex_sql
inputoutputformat_sql
national_sql
properties_sql
root_properties
properties
with_properties
locate_properties
property_name
property_sql
uuidproperty_sql
likeproperty_sql
fallbackproperty_sql
journalproperty_sql
freespaceproperty_sql
checksumproperty_sql
mergeblockratioproperty_sql
moduleproperty_sql
datablocksizeproperty_sql
blockcompressionproperty_sql
isolatedloadingproperty_sql
partitionboundspec_sql
partitionedofproperty_sql
lockingproperty_sql
lockingstatement_sql
withdataproperty_sql
withsystemversioningproperty_sql
insert_sql
introducer_sql
kill_sql
pseudotype_sql
objectidentifier_sql
onconflict_sql
rowformatdelimitedproperty_sql
withtablehint_sql
indextablehint_sql
historicaldata_sql
table_parts
table_sql
tableargument_sql
tablefromrows_sql
tablesample_sql
pivot_sql
tuple_sql
update_sql
values_sql
var_sql
from_sql
groupingsets_sql
rollup_sql
rollupindex_sql
rollupproperty_sql
cube_sql
group_sql
having_sql
connectto_sql
disconnect_sql
connect_sql
prior_sql
join_sql
nearest_sql
lambda_sql
lateral_sql
limit_sql
set_sql
queryband_sql
pragma_sql
lock_sql
literal_sql
escape_str
loaddata_sql
null_sql
booland_sql
boolor_sql
order_sql
withfill_sql
cluster_sql
clusterproperty_sql
distribute_sql
sort_sql
ordered_sql
matchrecognizemeasure_sql
matchrecognize_sql
query_modifiers
forclause_sql
offset_limit_modifiers
after_limit_modifiers
schema_sql
schema_columns_sql
star_sql
parameter_sql
sessionparameter_sql
placeholder_sql
subquery_sql
qualify_sql
unnest_sql
prewhere_sql
where_sql
window_sql
partition_by_sql
partitionbyexcluding_sql
windowspec_sql
withingroup_sql
between_sql
bracket_offset_expressions
bracket_sql
all_sql
any_sql
exists_sql
case_sql
nextvaluefor_sql
dayofweek_sql
extract_date_part
trim_sql
convert_concat_args
concat_sql
concatws_sql
check_sql
foreignkey_sql
primarykey_sql
timeserieskey_sql
if_sql
matchagainst_sql
jsonkeyvalue_sql
jsonpath_sql
json_path_part
format_sql
formatjson_sql
formatphrase_sql
teradataconversion_sql
teradatatitle_sql
teradatanamed_sql
jsonarray_sql
jsonarrayagg_sql
jsoncolumndef_sql
jsonschema_sql
jsontable_sql
openjsoncolumndef_sql
openjson_sql
in_sql
in_unnest_op
interval_sql
return_sql
reference_sql
anonymous_sql
paren_sql
pos_sql
neg_sql
not_sql
alias_sql
pivotalias_sql
aliases_sql
atindex_sql
attimezone_sql
fromtimezone_sql
fromiso8601date_sql
fromiso8601timestamp_sql
fromiso8601timestampnanos_sql
add_sql
and_sql
or_sql
xor_sql
connector_sql
bitwiseand_sql
bitwiseleftshift_sql
bitwisenot_sql
bitwiseor_sql
bitwiserightshift_sql
bitwisexor_sql
cast_sql
strtotime_sql
strtodate_sql
parsedatetime_sql
currentdate_sql
collate_sql
command_sql
optimize_sql
comment_sql
mergetreettlaction_sql
mergetreettl_sql
altercolumn_sql
modifycolumn_sql
alterindex_sql
alterdiststyle_sql
altersortkey_sql
alterrename_sql
renamecolumn_sql
alterset_sql
altersession_sql
add_column_sql
droppartition_sql
dropprimarykey_sql
addconstraint_sql
replacecolumns_sql
addpartition_sql
distinct_sql
ignorenulls_sql
respectnulls_sql
havingmax_sql
intdiv_sql
nullif_zero_divisor
div_sql
safedivide_sql
overlaps_sql
distance_sql
distancend_sql
dot_sql
nestedjsonselect_sql
eq_sql
propertyeq_sql
escape_sql
glob_sql
gt_sql
gte_sql
like_sql
ilike_sql
match_sql
similarto_sql
lt_sql
lte_sql
mod_sql
mul_sql
neq_sql
nullsafeeq_sql
nullsafeneq_sql
sub_sql
trycast_sql
jsoncast_sql
try_sql
log_sql
use_sql
binary
ceil_floor
function_fallback_sql
function_name
func
format_args
too_wide
format_time
expressions
op_expressions
naked_property
tag_sql
token_sql
userdefinedfunction_sql
macrooverloads_sql
macrooverload_sql
joinhint_sql
kwarg_sql
when_sql
whens_sql
merge_sql
tochar_sql
tonumber_sql
dictproperty_sql
dictrange_sql
dictsubproperty_sql
aggregatekeyproperty_sql
duplicatekeyproperty_sql
uniquekeyproperty_sql
distributedbyproperty_sql
oncluster_sql
clusteredbyproperty_sql
anyvalue_sql
querytransform_sql
indexconstraintoption_sql
checkcolumnconstraint_sql
indexcolumnconstraint_sql
nvl2_sql
nthvalue_sql
comprehension_sql
columnprefix_sql
opclass_sql
predict_sql
generateembedding_sql
generatetext_sql
generatetable_sql
generatebool_sql
generateint_sql
generatedouble_sql
mltranslate_sql
mlforecast_sql
aiforecast_sql
featuresattime_sql
vectorsearch_sql
forin_sql
refresh_sql
toarray_sql
tsordstotime_sql
tsordstotimestamp_sql
tsordstodatetime_sql
tsordstodate_sql
unixdate_sql
lastday_sql
dateadd_sql
arrayinsert_sql
arrayany_sql
struct_sql
partitionrange_sql
truncatetable_sql
copyparameter_sql
credentials_sql
copy_sql
semicolon_sql
datadeletionproperty_sql
maskingpolicycolumnconstraint_sql
gapfill_sql
scoperesolution_sql
parsejson_sql
rand_sql
changes_sql
pad_sql
summarize_sql
explodinggenerateseries_sql
converttimezone_sql
json_sql
jsonvalue_sql
skipjsoncolumn_sql
conditionalinsert_sql
multitableinserts_sql
oncondition_sql
jsonextractquote_sql
jsonexists_sql
min_sql
max_sql
arrayagg_sql
timeslice_sql
slice_sql
apply_sql
grant_sql
revoke_sql
grantprivilege_sql
grantprincipal_sql
columns_sql
overlay_sql
todouble_sql
string_sql
median_sql
overflowtruncatebehavior_sql
unixseconds_sql
arraysort_sql
variance_sql
arraysize_sql
attach_sql
detach_sql
attachoption_sql
watermarkcolumnconstraint_sql
encodeproperty_sql
includeproperty_sql
xmlelement_sql
xmlkeyvalueoption_sql
partitionbyrangeproperty_sql
partitionbyrangepropertydynamic_sql
unpivotcolumns_sql
analyzesample_sql
analyzestatistics_sql
analyzehistogram_sql
analyzedelete_sql
analyzelistchainedrows_sql
analyzevalidate_sql
analyze_sql
xmltable_sql
xmlnamespace_sql
export_sql
declare_sql
declareitem_sql
recursivewithsearch_sql
parameterizedagg_sql
anonymousaggfunc_sql
combinedaggfunc_sql
combinedparameterizedagg_sql
show_sql
install_sql
liststage_sql
get_put_sql
translatecharacters_sql
decodecase_sql
semanticview_sql
getextract_sql
datefromunixdate_sql
space_sql
buildproperty_sql
refreshtriggerproperty_sql
modelattribute_sql
directorystage_sql
uuid_sql
initcap_sql
localtime_sql
localtimestamp_sql
weekstart_name
weekstart_sql
chr_sql
weightstring_sql
block_sql
functionspecification_sql
casestatement_sql
loopblock_sql
repeatblock_sql
leave_sql
iterate_sql
executeimmediate_sql
altermodifysqlsecurity_sql
usingproperty_sql
renameindex_sql