Edit on GitHub

sqlglot.generators.bigquery

   1from __future__ import annotations
   2
   3import logging
   4import re
   5import typing as t
   6from decimal import Decimal
   7from fractions import Fraction
   8
   9from sqlglot import exp, generator, transforms
  10from sqlglot.dialects.dialect import (
  11    arg_max_or_min_no_count,
  12    array_sort_order,
  13    date_add_interval_sql,
  14    datestrtodate_sql,
  15    filter_array_using_unnest,
  16    generate_series_sql,
  17    if_sql,
  18    inline_array_unless_query,
  19    max_or_greatest,
  20    min_or_least,
  21    no_filter_sql,
  22    no_ilike_sql,
  23    regexp_replace_sql,
  24    rename_func,
  25    sha256_sql,
  26    timestrtotime_sql,
  27    ts_or_ds_add_cast,
  28    unit_to_var,
  29    strposition_sql,
  30    groupconcat_sql,
  31    sha2_digest_sql,
  32)
  33from sqlglot.errors import ErrorLevel
  34from sqlglot.generator import unsupported_args
  35from sqlglot.helper import seq_get
  36from sqlglot.optimizer.scope import find_in_scope
  37from sqlglot.typing import TIMESTAMP_EXPRESSIONS
  38
  39if t.TYPE_CHECKING:
  40    from sqlglot.dialects.dialect import DialectType
  41
  42logger = logging.getLogger("sqlglot")
  43
  44JSON_EXTRACT_TYPE = t.Union[exp.JSONExtract, exp.JSONExtractScalar, exp.JSONExtractArray]
  45
  46DQUOTES_ESCAPING_JSON_FUNCTIONS = ("JSON_QUERY", "JSON_VALUE", "JSON_QUERY_ARRAY")
  47
  48# BigQuery's DATE_ADD, DATE_SUB, TIMESTAMP_TRUNC, TIMESTAMP_ADD and TIMESTAMP_SUB return their first
  49# argument's type, as parentheses do
  50FIRST_ARG_TYPED = (
  51    exp.Paren,
  52    exp.DateAdd,
  53    exp.DateSub,
  54    exp.TimestampTrunc,
  55    exp.TimestampAdd,
  56    exp.TimestampSub,
  57)
  58
  59# Expressions BigQuery writes as a TIMESTAMP, e.g. AT TIME ZONE as TIMESTAMP(DATETIME(x, zone))
  60TIMESTAMP_TYPED = (exp.AtTimeZone, *TIMESTAMP_EXPRESSIONS)
  61
  62# Types BigQuery writes as DATETIME and as TIMESTAMP
  63ZONELESS_TYPES = {exp.DType.DATETIME, exp.DType.TIMESTAMP, exp.DType.TIMESTAMPNTZ}
  64ZONED_TYPES = {exp.DType.TIMESTAMPTZ, exp.DType.TIMESTAMPLTZ}
  65
  66
  67def _cast_zoneless_operand(expression: exp.Binary) -> None:
  68    # BigQuery can't compare a DATETIME with a TIMESTAMP, while engines like Trino read the
  69    # zoneless side in the session time zone. When both sides' types are known, e.g. from
  70    # annotate_types, the DATETIME side is cast to TIMESTAMP, which BigQuery reads as UTC
  71    left, right = expression.this, expression.expression
  72    left_type, right_type = left.type, right.type
  73    if left_type is None or right_type is None:
  74        return
  75
  76    if left_type.this in ZONELESS_TYPES and right_type.this in ZONED_TYPES:
  77        expression.set("this", exp.cast(left, exp.DType.TIMESTAMPTZ, copy=False))
  78    elif left_type.this in ZONED_TYPES and right_type.this in ZONELESS_TYPES:
  79        expression.set("expression", exp.cast(right, exp.DType.TIMESTAMPTZ, copy=False))
  80
  81
  82def _comparison_sql(op: str) -> t.Callable[[BigQueryGenerator, exp.Binary], str]:
  83    def _sql(self: BigQueryGenerator, expression: exp.Binary) -> str:
  84        _cast_zoneless_operand(expression)
  85        return self.binary(expression, op)
  86
  87    return _sql
  88
  89
  90# DATE_DIFF parts that BigQuery only takes for DATE or DATETIME operands
  91DATE_DIFF_DATETIME_UNITS = {"WEEK", "ISOWEEK", "MONTH", "QUARTER", "YEAR", "ISOYEAR"}
  92
  93# Expressions BigQuery writes as a DATETIME, e.g. DATETIME(x)
  94DATETIME_TYPED = (exp.CurrentDatetime, exp.TsOrDsToDatetime)
  95
  96
  97def _is_timestamp(node: exp.Expr) -> bool:
  98    while isinstance(node, FIRST_ARG_TYPED):
  99        node = node.this
 100    # TIME_STR_TO_TIME is written as CAST(x AS DATETIME) without a zone, whatever its type
 101    if isinstance(node, exp.TimeStrToTime):
 102        return bool(node.args.get("zone"))
 103    return isinstance(node, TIMESTAMP_TYPED) or node.is_type(exp.DType.TIMESTAMPTZ)
 104
 105
 106def _datetime_operand(expression: exp.Expr, dialect: DialectType) -> exp.Expr:
 107    if (
 108        isinstance(expression, DATETIME_TYPED)
 109        or expression.is_type(exp.DType.DATETIME)
 110        # TIME_STR_TO_TIME is written as CAST(x AS DATETIME) without a zone
 111        or (isinstance(expression, exp.TimeStrToTime) and not expression.args.get("zone"))
 112    ):
 113        return expression
 114    return exp.cast(expression, exp.DType.DATETIME, dialect=dialect)
 115
 116
 117def _derived_table_values_to_unnest(self: BigQueryGenerator, expression: exp.Values) -> str:
 118    if not expression.find_ancestor(exp.From, exp.Join):
 119        return self.values_sql(expression)
 120
 121    structs = []
 122    alias = expression.args.get("alias")
 123    for tup in expression.find_all(exp.Tuple):
 124        field_aliases = (
 125            alias.columns
 126            if alias and alias.columns
 127            else (f"_c{i}" for i in range(len(tup.expressions)))
 128        )
 129        expressions = [
 130            exp.PropertyEQ(this=exp.to_identifier(name), expression=fld)
 131            for name, fld in zip(field_aliases, tup.expressions)
 132        ]
 133        structs.append(exp.Struct(expressions=expressions))
 134
 135    # Due to `UNNEST_COLUMN_ONLY`, it is expected that the table alias be contained in the columns expression
 136    alias_name_only = exp.TableAlias(columns=[alias.this]) if alias else None
 137    return self.unnest_sql(
 138        exp.Unnest(expressions=[exp.array(*structs, copy=False)], alias=alias_name_only)
 139    )
 140
 141
 142def _returnsproperty_sql(self: BigQueryGenerator, expression: exp.ReturnsProperty) -> str:
 143    this = expression.this
 144    if isinstance(this, exp.Schema):
 145        this = f"{self.sql(this, 'this')} <{self.expressions(this)}>"
 146    else:
 147        this = self.sql(this)
 148    return f"RETURNS {this}"
 149
 150
 151def _create_sql(self: BigQueryGenerator, expression: exp.Create) -> str:
 152    returns = expression.find(exp.ReturnsProperty)
 153    if expression.kind == "FUNCTION" and returns and returns.args.get("is_table"):
 154        expression.set("kind", "TABLE FUNCTION")
 155
 156        if isinstance(expression.expression, (exp.Subquery, exp.Literal)):
 157            expression.set("expression", expression.expression.this)
 158
 159    return self.create_sql(expression)
 160
 161
 162# https://issuetracker.google.com/issues/162294746
 163# workaround for bigquery bug when grouping by an expression and then ordering
 164# WITH x AS (SELECT 1 y)
 165# SELECT y + 1 z
 166# FROM x
 167# GROUP BY x + 1
 168# ORDER by z
 169def _alias_ordered_group(expression: exp.Expr) -> exp.Expr:
 170    if isinstance(expression, exp.Select):
 171        group = expression.args.get("group")
 172        order = expression.args.get("order")
 173
 174        if group and order:
 175            aliases = {
 176                select.this: select.args["alias"]
 177                for select in expression.selects
 178                if isinstance(select, exp.Alias)
 179            }
 180
 181            for grouped in group.expressions:
 182                if grouped.is_int:
 183                    continue
 184                alias = aliases.get(grouped)
 185                if alias:
 186                    grouped.replace(exp.column(alias))
 187
 188    return expression
 189
 190
 191def _is_value_window(window: exp.Window) -> bool:
 192    func = window.this
 193    if isinstance(func, (exp.IgnoreNulls, exp.RespectNulls)):
 194        func = func.this
 195    return isinstance(func, (exp.FirstValue, exp.LastValue, exp.NthValue))
 196
 197
 198def _nondefault_null_order(ordered: exp.Expr) -> bool:
 199    # BigQuery sorts NULLs first in ascending order and last in descending order.
 200    return isinstance(ordered, exp.Ordered) and bool(ordered.args.get("nulls_first")) == bool(
 201        ordered.args.get("desc")
 202    )
 203
 204
 205def _inline_value_window_order(window: exp.Window, inherited: exp.Window) -> bool:
 206    order = inherited.args.get("order") or window.args.get("order")
 207    spec = window.args.get("spec") or inherited.args.get("spec")
 208    return bool(
 209        order
 210        and _is_value_window(window)
 211        and (not spec or spec.text("kind").upper() == "RANGE")
 212        and any(_nondefault_null_order(key) for key in order.expressions)
 213    )
 214
 215
 216def _pushdown_cte_column_names(expression: exp.Expr) -> exp.Expr:
 217    """BigQuery doesn't allow column names when defining a CTE, so we try to push them down."""
 218    if isinstance(expression, exp.CTE) and expression.alias_column_names:
 219        cte_query = expression.this
 220
 221        if cte_query.is_star:
 222            logger.warning(
 223                "Can't push down CTE column names for star queries. Run the query through"
 224                " the optimizer or use 'qualify' to expand the star projections first."
 225            )
 226            return expression
 227
 228        column_names = expression.alias_column_names
 229        expression.args["alias"].set("columns", None)
 230
 231        for name, select in zip(column_names, cte_query.selects):
 232            to_replace = select
 233
 234            if isinstance(select, exp.Alias):
 235                select = select.this
 236
 237            # Inner aliases are shadowed by the CTE column names
 238            to_replace.replace(exp.alias_(select, name))
 239
 240    return expression
 241
 242
 243def _unnest_explode_generate_series(expression: exp.Expr) -> exp.Expr:
 244    """
 245    Rewrites exploding GENERATE_SERIES projections into table references, e.g.
 246
 247        SELECT GENERATE_SERIES(1, 2) AS x           -> SELECT x FROM GENERATE_SERIES(1, 2) AS x
 248        SELECT y, GENERATE_SERIES(1, 2) AS x FROM t -> SELECT y, x FROM t CROSS JOIN GENERATE_SERIES(1, 2) AS x
 249
 250    since BigQuery can't explode in the projection and must unnest it in the FROM clause instead.
 251    The resulting table reference is unnested downstream by `transforms.unnest_generate_series`.
 252    """
 253    if isinstance(expression, exp.Select):
 254        for projection in expression.selects:
 255            if isinstance(series := projection.unalias(), exp.ExplodingGenerateSeries):
 256                column_name = projection.output_name or "_gen_series_value"
 257
 258                projection.replace(exp.column(column_name))
 259                table = exp.Table(
 260                    this=series, alias=exp.TableAlias(this=exp.to_identifier(column_name))
 261                )
 262
 263                if expression.args.get("from_"):
 264                    expression.join(table, copy=False, join_type="CROSS")
 265                else:
 266                    expression.set("from_", exp.From(this=table))
 267
 268    return expression
 269
 270
 271def _add_single_row_source(expression: exp.Expr) -> exp.Expr:
 272    """
 273    BigQuery rejects a query without a FROM clause when it has a WHERE, GROUP BY, HAVING, QUALIFY,
 274    ORDER BY or WINDOW clause, SELECT DISTINCT, or an aggregate or analytic function, so we add a
 275    single-row source, e.g. `SELECT COUNT(*)` becomes `SELECT COUNT(*) FROM (SELECT 1)`. The
 276    source must stay unaliased, otherwise it captures correlated references meant for the outer
 277    query.
 278    """
 279    if not isinstance(expression, exp.Select) or expression.args.get("from_"):
 280        return expression
 281
 282    if any(
 283        expression.args.get(arg)
 284        for arg in ("where", "group", "having", "qualify", "order", "distinct", "windows")
 285    ) or any(find_in_scope(p, exp.AggFunc, exp.Window) for p in expression.expressions):
 286        expression.set("from_", exp.From(this=exp.select("1").subquery()))
 287
 288    return expression
 289
 290
 291def _array_contains_sql(self: BigQueryGenerator, expression: exp.ArrayContains) -> str:
 292    return self.sql(
 293        exp.Exists(
 294            this=exp.select("1")
 295            .from_(exp.Unnest(expressions=[expression.left]).as_("_unnest", table=["_col"]))
 296            .where(exp.column("_col").eq(expression.right))
 297        )
 298    )
 299
 300
 301def _widen_decimal(expression: exp.Expr) -> exp.Expr:
 302    # NUMERIC holds at most 29 integer and 9 fractional digits, e.g. DECIMAL(38, 0) needs BIGNUMERIC
 303    for node in expression.find_all(exp.DataType):
 304        if node.is_type(exp.DType.DECIMAL) and node.expressions:
 305            precision, *rest = (param.this for param in node.expressions)
 306            scale = rest[0] if rest else exp.Literal.number(0)
 307            if precision.is_int and scale.is_int:
 308                scale_digits = int(scale.name)
 309                if int(precision.name) - scale_digits > 29 or scale_digits > 9:
 310                    node.set("this", exp.DType.BIGDECIMAL)
 311    return expression
 312
 313
 314def _extract_part(part: str) -> t.Callable[[BigQueryGenerator, exp.Func], str]:
 315    return lambda self, e: self.sql(exp.func("EXTRACT", exp.var(part), e.this, copy=False))
 316
 317
 318def _day_of_week_iso_sql(self: BigQueryGenerator, expression: exp.DayOfWeekIso) -> str:
 319    # DAYOFWEEK is Sunday=1..Saturday=7, ISO is Monday=1..Sunday=7
 320    template: exp.Expr = exp.maybe_parse("(MOD(EXTRACT(DAYOFWEEK FROM :this) + 5, 7) + 1)")
 321    return self.sql(exp.replace_placeholders(template, this=expression.this))
 322
 323
 324def _array_agg_fold_sql(
 325    self: BigQueryGenerator, expression: exp.ArrayDistinct | exp.ArraySort
 326) -> str:
 327    distinct = False
 328    ignore_nulls = False
 329    sort: exp.ArraySort | None = None
 330    agg: exp.Expr = expression
 331    while isinstance(agg, (exp.ArrayDistinct, exp.ArraySort)) and not agg.expression:
 332        if isinstance(agg, exp.ArrayDistinct):
 333            distinct = True
 334            ignore_nulls |= agg.args.get("check_null") is False
 335        elif sort is None:
 336            sort = agg
 337        agg = agg.this
 338
 339    order = array_sort_order(sort) if sort else None
 340
 341    condition = None
 342    if isinstance(agg, exp.Filter):
 343        condition, agg = agg.expression.this, agg.this
 344
 345    # An ARRAY_AGG with its own ORDER BY or LIMIT can't take another
 346    if (
 347        not isinstance(agg, exp.ArrayAgg)
 348        or isinstance(agg.this, (exp.Order, exp.Limit))
 349        or (sort is not None and order is None)
 350    ):
 351        self.unsupported(
 352            f"{expression.sql_name()} is only supported on an ARRAY_AGG without ORDER BY or LIMIT and with a literal order"
 353        )
 354        return self.func(expression.sql_name(), expression.this, expression.expression)
 355
 356    value = agg.this
 357    if isinstance(value, exp.Distinct):
 358        distinct, value = True, value.expressions[0]
 359    kept_nulls: exp.Expr | None = None
 360    if condition is not None:
 361        if not ignore_nulls and not agg.args.get("nulls_excluded"):
 362            # A kept NULL contributes [NULL], a kept value contributes [], and a rejected row
 363            # contributes no array. ARRAY_CONCAT_AGG returns NULL when no rows qualify.
 364            nulls = exp.If(
 365                this=value.is_(exp.null()),
 366                true=exp.Array(expressions=[value.copy()], value_constructor=True),
 367                false=exp.array(),
 368            )
 369            kept_nulls = exp.ArrayConcatAgg(
 370                this=exp.If(this=condition.copy(), true=nulls, false=exp.null())
 371            )
 372            if distinct:
 373                kept_nulls = exp.func("ARRAY_SLICE", kept_nulls, 0, 0)
 374
 375        # With DISTINCT, BigQuery only orders by the aggregated value, so the keys take the IF too
 376        value = exp.If(this=condition, true=value, false=exp.null())
 377        agg.set("nulls_excluded", None)
 378
 379    folded: exp.Expr = exp.Distinct(expressions=[value]) if distinct else value
 380    nulls_first = False
 381    if order is not None:
 382        asc, placement = order
 383        nulls_first = asc if placement is None else placement
 384        keys = [exp.Ordered(this=value.copy(), desc=not asc or None, nulls_first=asc)]
 385
 386        # Aggregate ORDER BY only puts NULLs first when ascending, so other placements need a key
 387        if not ignore_nulls and condition is None and nulls_first != asc:
 388            if distinct:
 389                self.unsupported("ARRAY_AGG(DISTINCT) only puts NULLs first when ascending")
 390            else:
 391                is_null = value.copy().is_(exp.null())
 392                keys.insert(
 393                    0,
 394                    exp.Ordered(
 395                        this=is_null, desc=nulls_first or None, nulls_first=not nulls_first
 396                    ),
 397                )
 398        folded = exp.Order(this=folded, expressions=keys)
 399    agg.set("this", folded)
 400    if ignore_nulls or condition is not None:
 401        agg = exp.func("COALESCE", exp.IgnoreNulls(this=agg), exp.array())
 402    if ignore_nulls:
 403        # All-NULL input yields [], but an empty input still yields NULL.
 404        rows = exp.CountIf(this=condition.copy()) if condition else exp.Count(this=exp.Star())
 405        agg = exp.If(
 406            this=rows.eq(0),
 407            true=exp.null(),
 408            false=agg,
 409        )
 410    elif kept_nulls is not None:
 411        arrays = (kept_nulls, agg) if nulls_first else (agg, kept_nulls)
 412        return self.func("ARRAY_CONCAT", *arrays)
 413    return self.sql(agg)
 414
 415
 416def _ts_or_ds_add_sql(self: BigQueryGenerator, expression: exp.TsOrDsAdd) -> str:
 417    return date_add_interval_sql("DATE", "ADD")(self, ts_or_ds_add_cast(expression))
 418
 419
 420def _ts_or_ds_diff_sql(self: BigQueryGenerator, expression: exp.TsOrDsDiff) -> str:
 421    expression.this.replace(exp.cast(expression.this, exp.DType.TIMESTAMP))
 422    expression.expression.replace(exp.cast(expression.expression, exp.DType.TIMESTAMP))
 423    unit = unit_to_var(expression)
 424    return self.func("DATE_DIFF", expression.this, expression.expression, unit)
 425
 426
 427def _unix_to_time_sql(self: BigQueryGenerator, expression: exp.UnixToTime) -> str:
 428    scale = expression.args.get("scale")
 429    timestamp = expression.this
 430
 431    if scale in (None, exp.UnixToTime.SECONDS):
 432        return self.func("TIMESTAMP_SECONDS", timestamp)
 433    if scale == exp.UnixToTime.MILLIS:
 434        return self.func("TIMESTAMP_MILLIS", timestamp)
 435    if scale == exp.UnixToTime.MICROS:
 436        return self.func("TIMESTAMP_MICROS", timestamp)
 437
 438    unix_seconds = exp.cast(
 439        exp.Div(this=timestamp, expression=exp.func("POW", 10, scale)), exp.DType.BIGINT
 440    )
 441    return self.func("TIMESTAMP_SECONDS", unix_seconds)
 442
 443
 444def _str_to_datetime_sql(self: BigQueryGenerator, expression: exp.StrToDate | exp.StrToTime) -> str:
 445    this = self.sql(expression, "this")
 446    dtype = "DATE" if isinstance(expression, exp.StrToDate) else "TIMESTAMP"
 447
 448    if expression.args.get("safe"):
 449        fmt = self.format_time(
 450            expression,
 451            self.dialect.INVERSE_FORMAT_MAPPING,
 452            self.dialect.INVERSE_FORMAT_TRIE,
 453        )
 454        return f"SAFE_CAST({this} AS {dtype} FORMAT {fmt})"
 455
 456    fmt = self.format_time(expression)
 457    return self.func(f"PARSE_{dtype}", fmt, this, expression.args.get("zone"))
 458
 459
 460@unsupported_args("ins_cost", "del_cost", "sub_cost")
 461def _levenshtein_sql(self: BigQueryGenerator, expression: exp.Levenshtein) -> str:
 462    max_dist = expression.args.get("max_dist")
 463    if max_dist:
 464        max_dist = exp.Kwarg(this=exp.var("max_distance"), expression=max_dist)
 465
 466    return self.func("EDIT_DISTANCE", expression.this, expression.expression, max_dist)
 467
 468
 469def _json_extract_sql(self: BigQueryGenerator, expression: JSON_EXTRACT_TYPE) -> str:
 470    upper = self.function_name(expression).upper()
 471
 472    dquote_escaping = upper in DQUOTES_ESCAPING_JSON_FUNCTIONS
 473
 474    if dquote_escaping:
 475        self._quote_json_path_key_using_brackets = False
 476
 477    sql = rename_func(upper)(self, expression)
 478
 479    if dquote_escaping:
 480        self._quote_json_path_key_using_brackets = True
 481
 482    return sql
 483
 484
 485class BigQueryGenerator(generator.Generator):
 486    TRY_SUPPORTED = False
 487    SUPPORTS_UESCAPE = False
 488    SUPPORTS_DECODE_CASE = False
 489    SUPPORTS_MULTI_ARG_CHR = False
 490    INTERVAL_ALLOWS_PLURAL_FORM = False
 491    JOIN_HINTS = False
 492    QUERY_HINTS = False
 493    TABLE_HINTS = False
 494    LIMIT_FETCH = "LIMIT"
 495    RENAME_TABLE_WITH_DB = False
 496    NVL2_SUPPORTED = False
 497    UNNEST_WITH_ORDINALITY = False
 498    CAST_TO_INT_ROUNDS = True
 499    COLLATE_IS_FUNC = True
 500    LIMIT_ONLY_LITERALS = True
 501    SUPPORTS_TABLE_ALIAS_COLUMNS = False
 502    SUPPORTS_NAMED_CTE_COLUMNS = False
 503    UNPIVOT_ALIASES_ARE_IDENTIFIERS = False
 504    JSON_KEY_VALUE_PAIR_SEP = ","
 505    NULL_ORDERING_SUPPORTED: bool | None = False
 506    IGNORE_NULLS_IN_FUNC = True
 507    JSON_PATH_SINGLE_QUOTE_ESCAPE = True
 508    CAN_IMPLEMENT_ARRAY_ANY = True
 509    SUPPORTS_TO_NUMBER = False
 510    NAMED_PLACEHOLDER_TOKEN = "@"
 511    HEX_FUNC = "TO_HEX"
 512    WITH_PROPERTIES_PREFIX = "OPTIONS"
 513    SUPPORTS_EXPLODING_PROJECTIONS = False
 514    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
 515    SUPPORTS_UNIX_SECONDS = True
 516    DECLARE_DEFAULT_ASSIGNMENT = "DEFAULT"
 517
 518    SAFE_JSON_PATH_KEY_RE = re.compile(r"^[\-\w]*$")
 519
 520    WINDOW_FUNCS_REQUIRING_ORDER = (
 521        exp.CumeDist,
 522        exp.DenseRank,
 523        exp.FirstValue,
 524        exp.LastValue,
 525        exp.NthValue,
 526        exp.Ntile,
 527        exp.PercentRank,
 528        exp.Rank,
 529    )
 530
 531    WINDOW_FUNCS_WITH_NULL_ORDERING = (
 532        exp.CumeDist,
 533        exp.DenseRank,
 534        exp.FirstValue,
 535        exp.Lag,
 536        exp.LastValue,
 537        exp.Lead,
 538        exp.NthValue,
 539        exp.Ntile,
 540        exp.PercentRank,
 541        exp.Rank,
 542        exp.RowNumber,
 543    )
 544
 545    TS_OR_DS_TYPES: t.ClassVar = (
 546        exp.TsOrDsToDatetime,
 547        exp.TsOrDsToTimestamp,
 548        exp.TsOrDsToTime,
 549        exp.TsOrDsToDate,
 550    )
 551
 552    TRANSFORMS = {
 553        **generator.Generator.TRANSFORMS,
 554        exp.AIEmbed: rename_func("EMBED"),
 555        exp.AIGenerate: rename_func("GENERATE"),
 556        exp.AISimilarity: rename_func("SIMILARITY"),
 557        exp.ApproxTopK: rename_func("APPROX_TOP_COUNT"),
 558        exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"),
 559        exp.ArgMax: arg_max_or_min_no_count("MAX_BY"),
 560        exp.ArgMin: arg_max_or_min_no_count("MIN_BY"),
 561        exp.Array: inline_array_unless_query,
 562        exp.ArrayContains: _array_contains_sql,
 563        exp.ArrayDistinct: _array_agg_fold_sql,
 564        exp.ArraySort: _array_agg_fold_sql,
 565        exp.ArrayFilter: filter_array_using_unnest,
 566        exp.ArrayRemove: filter_array_using_unnest,
 567        exp.BitwiseAndAgg: rename_func("BIT_AND"),
 568        exp.BitwiseOrAgg: rename_func("BIT_OR"),
 569        exp.BitwiseXorAgg: rename_func("BIT_XOR"),
 570        exp.BitwiseCount: rename_func("BIT_COUNT"),
 571        exp.ByteLength: rename_func("BYTE_LENGTH"),
 572        exp.Cast: transforms.preprocess(
 573            [_widen_decimal, transforms.remove_precision_parameterized_types]
 574        ),
 575        exp.TryCast: transforms.preprocess(
 576            [_widen_decimal, transforms.remove_precision_parameterized_types]
 577        ),
 578        exp.CollateProperty: lambda self, e: (
 579            f"DEFAULT COLLATE {self.sql(e, 'this')}"
 580            if e.args.get("default")
 581            else f"COLLATE {self.sql(e, 'this')}"
 582        ),
 583        exp.Commit: lambda *_: "COMMIT TRANSACTION",
 584        exp.CountIf: rename_func("COUNTIF"),
 585        exp.Create: _create_sql,
 586        exp.CTE: transforms.preprocess([_pushdown_cte_column_names]),
 587        exp.DateFromParts: rename_func("DATE"),
 588        exp.DateStrToDate: datestrtodate_sql,
 589        exp.DatetimeAdd: date_add_interval_sql("DATETIME", "ADD"),
 590        exp.DatetimeSub: date_add_interval_sql("DATETIME", "SUB"),
 591        exp.DateFromUnixDate: rename_func("DATE_FROM_UNIX_DATE"),
 592        exp.Day: _extract_part("DAY"),
 593        exp.DayOfMonth: _extract_part("DAY"),
 594        exp.DayOfWeekIso: _day_of_week_iso_sql,
 595        exp.DayOfYear: _extract_part("DAYOFYEAR"),
 596        exp.Filter: no_filter_sql,
 597        exp.FromTimeZone: lambda self, e: self.func(
 598            "DATETIME", self.func("TIMESTAMP", e.this, e.args.get("zone")), "'UTC'"
 599        ),
 600        exp.GenerateSeries: generate_series_sql("GENERATE_ARRAY"),
 601        exp.GroupConcat: lambda self, e: groupconcat_sql(
 602            self, e, func_name="STRING_AGG", within_group=False, sep=None
 603        ),
 604        exp.GT: _comparison_sql(">"),
 605        exp.GTE: _comparison_sql(">="),
 606        exp.Hex: lambda self, e: self.func("UPPER", self.func("TO_HEX", self.sql(e, "this"))),
 607        exp.HexString: lambda self, e: self.hexstring_sql(e, binary_function_repr="FROM_HEX"),
 608        exp.Hour: _extract_part("HOUR"),
 609        exp.If: if_sql(false_value="NULL"),
 610        exp.ILike: no_ilike_sql,
 611        exp.IntDiv: rename_func("DIV"),
 612        exp.Int64: rename_func("INT64"),
 613        exp.JSONBool: rename_func("BOOL"),
 614        exp.JSONExtract: _json_extract_sql,
 615        exp.JSONExtractArray: _json_extract_sql,
 616        exp.JSONExtractScalar: _json_extract_sql,
 617        exp.JSONFormat: lambda self, e: self.func(
 618            "TO_JSON" if e.args.get("to_json") else "TO_JSON_STRING",
 619            e.this,
 620            e.args.get("options"),
 621        ),
 622        exp.JSONKeysAtDepth: rename_func("JSON_KEYS"),
 623        exp.JSONValueArray: rename_func("JSON_VALUE_ARRAY"),
 624        exp.Levenshtein: _levenshtein_sql,
 625        exp.LT: _comparison_sql("<"),
 626        exp.LTE: _comparison_sql("<="),
 627        exp.Max: max_or_greatest,
 628        exp.MD5: lambda self, e: self.func("TO_HEX", self.func("MD5", e.this)),
 629        exp.MD5Digest: rename_func("MD5"),
 630        exp.Min: min_or_least,
 631        exp.Month: _extract_part("MONTH"),
 632        exp.NEQ: _comparison_sql("<>"),
 633        exp.Normalize: lambda self, e: self.func(
 634            "NORMALIZE_AND_CASEFOLD" if e.args.get("is_casefold") else "NORMALIZE",
 635            e.this,
 636            e.args.get("form"),
 637        ),
 638        exp.NullSafeEQ: _comparison_sql("IS NOT DISTINCT FROM"),
 639        exp.NullSafeNEQ: _comparison_sql("IS DISTINCT FROM"),
 640        exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
 641        exp.Quarter: _extract_part("QUARTER"),
 642        exp.RegexpExtract: lambda self, e: self.func(
 643            "REGEXP_EXTRACT",
 644            e.this,
 645            e.expression,
 646            e.args.get("position"),
 647            e.args.get("occurrence"),
 648        ),
 649        exp.RegexpExtractAll: lambda self, e: self.func("REGEXP_EXTRACT_ALL", e.this, e.expression),
 650        exp.RegexpReplace: regexp_replace_sql,
 651        exp.RegexpLike: rename_func("REGEXP_CONTAINS"),
 652        exp.ReturnsProperty: _returnsproperty_sql,
 653        exp.Rollback: lambda *_: "ROLLBACK TRANSACTION",
 654        exp.ParseTime: lambda self, e: self.func("PARSE_TIME", self.format_time(e), e.this),
 655        exp.ParseDatetime: lambda self, e: self.func("PARSE_DATETIME", self.format_time(e), e.this),
 656        exp.Select: transforms.preprocess(
 657            [
 658                _unnest_explode_generate_series,
 659                transforms.explode_projection_to_unnest(),
 660                transforms.unqualify_unnest,
 661                transforms.eliminate_distinct_on,
 662                _alias_ordered_group,
 663                lambda e: transforms.eliminate_window_clause(e, _inline_value_window_order),
 664                transforms.eliminate_semi_and_anti_joins,
 665                _add_single_row_source,
 666            ]
 667        ),
 668        exp.SHA: rename_func("SHA1"),
 669        exp.SHA2: sha256_sql,
 670        exp.SHA1Digest: rename_func("SHA1"),
 671        exp.SHA2Digest: sha2_digest_sql,
 672        exp.StabilityProperty: lambda self, e: (
 673            "DETERMINISTIC" if e.name == "IMMUTABLE" else "NOT DETERMINISTIC"
 674        ),
 675        exp.String: rename_func("STRING"),
 676        exp.StrPosition: lambda self, e: strposition_sql(
 677            self, e, func_name="INSTR", supports_position=True, supports_occurrence=True
 678        ),
 679        exp.StrToDate: _str_to_datetime_sql,
 680        exp.StrToTime: _str_to_datetime_sql,
 681        exp.SessionUser: lambda *_: "SESSION_USER()",
 682        exp.Table: transforms.preprocess([transforms.unnest_generate_series]),
 683        exp.TimeAdd: date_add_interval_sql("TIME", "ADD"),
 684        exp.TimeFromParts: rename_func("TIME"),
 685        exp.TimestampFromParts: rename_func("DATETIME"),
 686        exp.TimeSub: date_add_interval_sql("TIME", "SUB"),
 687        exp.TimestampAdd: date_add_interval_sql("TIMESTAMP", "ADD"),
 688        exp.TimestampDiff: lambda self, e: self.func(
 689            "TIMESTAMP_DIFF", e.this, e.expression, e.unit
 690        ),
 691        exp.TimestampSub: date_add_interval_sql("TIMESTAMP", "SUB"),
 692        exp.TimeStrToTime: timestrtotime_sql,
 693        exp.Transaction: lambda *_: "BEGIN TRANSACTION",
 694        exp.TsOrDsAdd: _ts_or_ds_add_sql,
 695        exp.TsOrDsDiff: _ts_or_ds_diff_sql,
 696        exp.TsOrDsToTime: rename_func("TIME"),
 697        exp.TsOrDsToDatetime: rename_func("DATETIME"),
 698        exp.TsOrDsToTimestamp: rename_func("TIMESTAMP"),
 699        exp.Unhex: rename_func("FROM_HEX"),
 700        exp.UnixDate: rename_func("UNIX_DATE"),
 701        exp.UnixToTime: _unix_to_time_sql,
 702        exp.Uuid: lambda *_: "GENERATE_UUID()",
 703        exp.Values: _derived_table_values_to_unnest,
 704        exp.VariancePop: rename_func("VAR_POP"),
 705        exp.WeekOfYear: _extract_part("ISOWEEK"),
 706        exp.Year: _extract_part("YEAR"),
 707        exp.SafeDivide: rename_func("SAFE_DIVIDE"),
 708    }
 709
 710    SUPPORTED_JSON_PATH_PARTS = {
 711        exp.JSONPathKey,
 712        exp.JSONPathRoot,
 713        exp.JSONPathSubscript,
 714    }
 715
 716    TYPE_MAPPING = {
 717        **generator.Generator.TYPE_MAPPING,
 718        exp.DType.BIGDECIMAL: "BIGNUMERIC",
 719        exp.DType.BIGINT: "INT64",
 720        exp.DType.BINARY: "BYTES",
 721        exp.DType.BLOB: "BYTES",
 722        exp.DType.BOOLEAN: "BOOL",
 723        exp.DType.CHAR: "STRING",
 724        exp.DType.DECIMAL: "NUMERIC",
 725        exp.DType.DOUBLE: "FLOAT64",
 726        exp.DType.FLOAT: "FLOAT64",
 727        exp.DType.INT: "INT64",
 728        exp.DType.NCHAR: "STRING",
 729        exp.DType.NVARCHAR: "STRING",
 730        exp.DType.SMALLINT: "INT64",
 731        exp.DType.TEXT: "STRING",
 732        exp.DType.TIMESTAMP: "DATETIME",
 733        exp.DType.TIMESTAMPNTZ: "DATETIME",
 734        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
 735        exp.DType.TIMESTAMPLTZ: "TIMESTAMP",
 736        exp.DType.TINYINT: "INT64",
 737        exp.DType.ROWVERSION: "BYTES",
 738        exp.DType.UUID: "STRING",
 739        exp.DType.VARBINARY: "BYTES",
 740        exp.DType.VARCHAR: "STRING",
 741        exp.DType.VARIANT: "ANY TYPE",
 742    }
 743
 744    PROPERTIES_LOCATION = {
 745        **generator.Generator.PROPERTIES_LOCATION,
 746        exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
 747        exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
 748    }
 749
 750    # WINDOW comes after QUALIFY
 751    # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#window_clause
 752    # BigQuery requires QUALIFY before WINDOW
 753    AFTER_HAVING_MODIFIER_TRANSFORMS = {
 754        "qualify": generator.AFTER_HAVING_MODIFIER_TRANSFORMS["qualify"],
 755        "windows": generator.AFTER_HAVING_MODIFIER_TRANSFORMS["windows"],
 756    }
 757
 758    # from: https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#reserved_keywords
 759    RESERVED_KEYWORDS = {
 760        "all",
 761        "and",
 762        "any",
 763        "array",
 764        "as",
 765        "asc",
 766        "assert_rows_modified",
 767        "at",
 768        "between",
 769        "by",
 770        "case",
 771        "cast",
 772        "collate",
 773        "contains",
 774        "create",
 775        "cross",
 776        "cube",
 777        "current",
 778        "default",
 779        "define",
 780        "desc",
 781        "distinct",
 782        "else",
 783        "end",
 784        "enum",
 785        "escape",
 786        "except",
 787        "exclude",
 788        "exists",
 789        "extract",
 790        "false",
 791        "fetch",
 792        "following",
 793        "for",
 794        "from",
 795        "full",
 796        "group",
 797        "grouping",
 798        "groups",
 799        "hash",
 800        "having",
 801        "if",
 802        "ignore",
 803        "in",
 804        "inner",
 805        "intersect",
 806        "interval",
 807        "into",
 808        "is",
 809        "join",
 810        "lateral",
 811        "left",
 812        "like",
 813        "limit",
 814        "lookup",
 815        "merge",
 816        "natural",
 817        "new",
 818        "no",
 819        "not",
 820        "null",
 821        "nulls",
 822        "of",
 823        "on",
 824        "or",
 825        "order",
 826        "outer",
 827        "over",
 828        "partition",
 829        "preceding",
 830        "proto",
 831        "qualify",
 832        "range",
 833        "recursive",
 834        "respect",
 835        "right",
 836        "rollup",
 837        "rows",
 838        "select",
 839        "set",
 840        "some",
 841        "struct",
 842        "tablesample",
 843        "then",
 844        "to",
 845        "treat",
 846        "true",
 847        "unbounded",
 848        "union",
 849        "unnest",
 850        "using",
 851        "when",
 852        "where",
 853        "window",
 854        "with",
 855        "within",
 856    }
 857
 858    def __init__(
 859        self,
 860        pretty: bool | int | None = None,
 861        identify: str | bool = False,
 862        normalize: bool = False,
 863        pad: int = 2,
 864        indent: int = 2,
 865        normalize_functions: str | bool | None = None,
 866        unsupported_level: ErrorLevel = ErrorLevel.WARN,
 867        max_unsupported: int = 3,
 868        leading_comma: bool = False,
 869        max_text_width: int = 80,
 870        comments: bool = True,
 871        dialect: DialectType = None,
 872    ) -> None:
 873        super().__init__(
 874            pretty=pretty,
 875            identify=identify,
 876            normalize=normalize,
 877            pad=pad,
 878            indent=indent,
 879            normalize_functions=normalize_functions,
 880            unsupported_level=unsupported_level,
 881            max_unsupported=max_unsupported,
 882            leading_comma=leading_comma,
 883            max_text_width=max_text_width,
 884            comments=comments,
 885            dialect=dialect,
 886        )
 887
 888        self._escaped_identifier_end = r"\`"
 889
 890        # Escape existing backslashes before introducing new escape sequences.
 891        self._identifier_escaped_sequences = {
 892            **self._identifier_escaped_sequences,
 893            **self.dialect.ESCAPED_SEQUENCES,
 894        }
 895
 896    def frombase_sql(self, expression: exp.FromBase) -> str:
 897        # Hex is the only base BigQuery can cast from, and the sign goes before the prefix, e.g. -0xff
 898        if expression.expression.name != "16":
 899            self.unsupported("FROM_BASE is only supported for base 16")
 900            return self.function_fallback_sql(expression)
 901
 902        prefixed = exp.func(
 903            "REGEXP_REPLACE",
 904            expression.this,
 905            exp.Literal.string("^([+-]?)"),
 906            exp.Literal.string("\\10x"),
 907            copy=False,
 908        )
 909        return self.sql(exp.cast(prefixed, exp.DType.BIGINT, copy=False))
 910
 911    def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str:
 912        node: exp.Expr = expression
 913        while node.parent and not isinstance(node.parent, (exp.Window, exp.AggFunc, exp.Select)):
 914            node = node.parent
 915        if isinstance(node.parent, exp.Window) and node.arg_key == "this":
 916            self.unsupported("APPROX_QUANTILES does not support window functions")
 917            return self.function_fallback_sql(expression)
 918
 919        # The k/n quantile is APPROX_QUANTILES(x, n)[k], e.g. 0.95 -> n = 20, k = 19. n is at most
 920        # 100,000, so the quantile has at most 5 decimal places, and Decimal comparisons are exact
 921        quantile = expression.args["quantile"]
 922        weight = expression.args.get("weight")
 923        value = Decimal(quantile.to_py()) if quantile.is_number else None
 924        if (
 925            value is None
 926            or not 0 <= value <= 1
 927            or round(value, 5) != value
 928            or (weight and (not weight.is_number or weight.to_py() != 1))
 929        ):
 930            self.unsupported("APPROX_QUANTILE needs a literal quantile and no weight")
 931            return self.function_fallback_sql(expression)
 932
 933        fraction = Fraction(value)
 934        quantiles = exp.func("APPROX_QUANTILES", expression.this, fraction.denominator, copy=False)
 935        return self.sql(quantiles[fraction.numerator])
 936
 937    def weekstart_sql(self, expression: exp.WeekStart) -> str:
 938        if expression.this.name.upper() == "SUNDAY":
 939            # BigQuery specific optimization since WEEK(SUNDAY) == WEEK
 940            return "WEEK"
 941
 942        return self.func("WEEK", expression.this)
 943
 944    def dateadd_sql(self, expression: exp.DateAdd | exp.DateSub) -> str:
 945        kind = "SUB" if isinstance(expression, exp.DateSub) else "ADD"
 946        this = expression.this
 947        if expression.text("unit") in ("WEEK", "MONTH", "QUARTER", "YEAR") and _is_timestamp(this):
 948            # TIMESTAMP arithmetic only takes units up to DAY, so use the UTC DATETIME instead
 949            shifted = (exp.DatetimeSub if kind == "SUB" else exp.DatetimeAdd)(
 950                this=exp.TsOrDsToDatetime(this=this),
 951                expression=expression.expression,
 952                unit=expression.unit,
 953            )
 954            return self.func("TIMESTAMP", shifted)
 955
 956        return date_add_interval_sql("DATE", kind)(self, expression)
 957
 958    def datesub_sql(self, expression: exp.DateSub) -> str:
 959        return self.dateadd_sql(expression)
 960
 961    def datediff_sql(self, expression: exp.DateDiff) -> str:
 962        this = expression.this
 963        expr = expression.expression
 964        unit = expression.text("unit")
 965        if not isinstance(expression.unit, exp.WeekStart) and unit not in DATE_DIFF_DATETIME_UNITS:
 966            return self.func("DATE_DIFF", this, expr, unit_to_var(expression))
 967
 968        zoned_types = (exp.DType.TIMESTAMPTZ, exp.DType.TIMESTAMPLTZ)
 969        zoned = this.unnest().is_type(*zoned_types) or expr.unnest().is_type(*zoned_types)
 970        if zoned:
 971            self.unsupported("DATE_DIFF reads TIMESTAMP WITH TIME ZONE values in UTC")
 972
 973        if unit == "WEEK" and not expression.args.get("date_part_boundary"):
 974            self.unsupported("DATE_DIFF counts the Sundays crossed, not whole weeks")
 975
 976        if not zoned and not (_is_timestamp(this) or _is_timestamp(expr)):
 977            return self.func("DATE_DIFF", this, expr, unit_to_var(expression))
 978
 979        # These units only take DATE or DATETIME operands, so both sides are cast to DATETIME,
 980        # which reads a TIMESTAMP in UTC
 981        return self.func(
 982            "DATE_DIFF",
 983            _datetime_operand(this, self.dialect),
 984            _datetime_operand(expr, self.dialect),
 985            unit_to_var(expression),
 986        )
 987
 988    def datetrunc_sql(self, expression: exp.DateTrunc) -> str:
 989        self._warn_unsupported_arg(expression, "century_from_zero")
 990        unit = expression.unit
 991        if unit.is_string and unit.name.upper() in ("WEEK_OF_MONTH", "WEEK_OF_YEAR"):
 992            self.unsupported(f"Unexpected interval unit: {unit.name}")
 993        unit_sql = unit.name if unit.is_string else self.sql(unit)
 994        return self.func("DATE_TRUNC", expression.this, unit_sql, expression.args.get("zone"))
 995
 996    def mod_sql(self, expression: exp.Mod) -> str:
 997        self.nullif_zero_divisor(expression)
 998        this = expression.this
 999        expr = expression.expression
1000        return self.func(
1001            "MOD",
1002            this.unnest() if isinstance(this, exp.Paren) else this,
1003            expr.unnest() if isinstance(expr, exp.Paren) else expr,
1004        )
1005
1006    def column_parts(self, expression: exp.Column) -> str:
1007        if expression.meta_get("quoted_column"):
1008            # If a column reference is of the form `dataset.table`.name, we need
1009            # to preserve the quoted table path, otherwise the reference breaks
1010            table_parts = ".".join(p.name for p in expression.parts[:-1])
1011            table_path = self.sql(exp.Identifier(this=table_parts, quoted=True))
1012            return f"{table_path}.{self.sql(expression, 'this')}"
1013
1014        return super().column_parts(expression)
1015
1016    def table_parts(self, expression: exp.Table) -> str:
1017        # Depending on the context, `x.y` may not resolve to the same data source as `x`.`y`, so
1018        # we need to make sure the correct quoting is used in each case.
1019        #
1020        # For example, if there is a CTE x that clashes with a schema name, then the former will
1021        # return the table y in that schema, whereas the latter will return the CTE's y column:
1022        #
1023        # - WITH x AS (SELECT [1, 2] AS y) SELECT * FROM x, `x.y`   -> cross join
1024        # - WITH x AS (SELECT [1, 2] AS y) SELECT * FROM x, `x`.`y` -> implicit unnest
1025        if expression.meta_get("quoted_table"):
1026            table_parts = ".".join(p.name for p in expression.parts)
1027            return self.sql(exp.Identifier(this=table_parts, quoted=True))
1028
1029        return super().table_parts(expression)
1030
1031    def timetostr_sql(self, expression: exp.TimeToStr) -> str:
1032        this = expression.this
1033        if isinstance(this, exp.TsOrDsToDatetime):
1034            func_name = "FORMAT_DATETIME"
1035        elif isinstance(this, exp.TsOrDsToTimestamp):
1036            func_name = "FORMAT_TIMESTAMP"
1037        elif isinstance(this, exp.TsOrDsToTime):
1038            func_name = "FORMAT_TIME"
1039        else:
1040            func_name = "FORMAT_DATE"
1041
1042        time_expr = this if isinstance(this, self.TS_OR_DS_TYPES) else expression
1043        return self.func(
1044            func_name, self.format_time(expression), time_expr.this, expression.args.get("zone")
1045        )
1046
1047    def eq_sql(self, expression: exp.EQ) -> str:
1048        # Operands of = cannot be NULL in BigQuery
1049        if isinstance(expression.left, exp.Null) or isinstance(expression.right, exp.Null):
1050            if not isinstance(expression.parent, exp.Update):
1051                return "NULL"
1052
1053        _cast_zoneless_operand(expression)
1054        return self.binary(expression, "=")
1055
1056    def escape_sql(self, expression: exp.Escape) -> str:
1057        # BigQuery's LIKE has no ESCAPE clause and always escapes with a backslash, so a literal
1058        # pattern is rewritten to backslash escapes. UPPER/LOWER around it can't change a
1059        # caseless escape character, e.g. ^, so those patterns are rewritten too.
1060        like, char = expression.this.copy(), expression.expression.name
1061        pattern = like.expression
1062        if isinstance(pattern, (exp.Upper, exp.Lower)) and char.upper() == char.lower():
1063            pattern = pattern.this
1064        e = re.escape(char)
1065        if not (
1066            isinstance(like, exp.Like)
1067            and expression.expression.is_string
1068            and len(char) == 1
1069            and pattern.is_string
1070            and re.fullmatch(f"(?:[^{e}]|{e}[%_{e}])*", pattern.name)
1071        ):
1072            return super().escape_sql(expression)
1073
1074        # Escaped %, _ and backslash, and unescaped backslash, get a backslash
1075        pattern.set(
1076            "this",
1077            re.sub(
1078                f"{e}[%_{e}]|\\\\",
1079                lambda m: "\\" * (m[0][-1] in "%_\\") + m[0][-1],
1080                pattern.name,
1081            ),
1082        )
1083        return self.sql(like)
1084
1085    def _native_dayofweek_sql(self, expression: exp.DayOfWeek) -> str:
1086        return self.sql(exp.Extract(this=exp.var("DAYOFWEEK"), expression=expression.this))
1087
1088    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
1089        parent = expression.parent
1090
1091        # BigQuery allows CAST(.. AS {STRING|TIMESTAMP} [FORMAT <fmt> [AT TIME ZONE <tz>]]).
1092        # Only the TIMESTAMP one should use the below conversion, when AT TIME ZONE is included.
1093        if not isinstance(parent, exp.Cast) or not parent.to.is_type("text"):
1094            this = expression.this
1095            if expression.args.get("session_zone"):
1096                # DATETIME(<ts>, <zone>) only accepts a TIMESTAMP and BigQuery reads a DATETIME
1097                # cast to TIMESTAMP as UTC, so this assumes the source session time zone is UTC
1098                this = exp.cast(this, exp.DType.TIMESTAMPTZ)
1099
1100            return self.func("TIMESTAMP", self.func("DATETIME", this, expression.args.get("zone")))
1101
1102        return super().attimezone_sql(expression)
1103
1104    def trycast_sql(self, expression: exp.TryCast) -> str:
1105        return self.cast_sql(expression, safe_prefix="SAFE_")
1106
1107    def bracket_sql(self, expression: exp.Bracket) -> str:
1108        this = expression.this
1109        expressions = expression.expressions
1110
1111        if len(expressions) == 1 and this and this.is_type(exp.DType.STRUCT):
1112            arg = expressions[0]
1113            if arg.type is None:
1114                from sqlglot.optimizer.annotate_types import annotate_types
1115
1116                arg = annotate_types(arg, dialect=self.dialect)
1117
1118            if arg.type and arg.type.this in exp.DataType.TEXT_TYPES:
1119                # BQ doesn't support bracket syntax with string values for structs
1120                return f"{self.sql(this)}.{arg.name}"
1121
1122        expressions_sql = self.expressions(expression, flat=True)
1123        offset = expression.args.get("offset")
1124
1125        if offset == 0:
1126            expressions_sql = f"OFFSET({expressions_sql})"
1127        elif offset == 1:
1128            expressions_sql = f"ORDINAL({expressions_sql})"
1129        elif offset is not None:
1130            self.unsupported(f"Unsupported array offset: {offset}")
1131
1132        if expression.args.get("safe"):
1133            expressions_sql = f"SAFE_{expressions_sql}"
1134
1135        return f"{self.sql(this)}[{expressions_sql}]"
1136
1137    def in_unnest_op(self, expression: exp.Unnest) -> str:
1138        return self.sql(expression)
1139
1140    def version_sql(self, expression: exp.Version) -> str:
1141        if expression.name == "TIMESTAMP":
1142            expression.set("this", "SYSTEM_TIME")
1143        return super().version_sql(expression)
1144
1145    def contains_sql(self, expression: exp.Contains) -> str:
1146        this = expression.this
1147        expr = expression.expression
1148
1149        if isinstance(this, exp.Lower) and isinstance(expr, exp.Lower):
1150            this = this.this
1151            expr = expr.this
1152
1153        return self.func("CONTAINS_SUBSTR", this, expr, expression.args.get("json_scope"))
1154
1155    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
1156        if expression.args.get("is_literal"):
1157            return f"JSON {self.sql(expression, 'this')}"
1158        return super().parsejson_sql(expression)
1159
1160    def stgeogfromgeojson_sql(self, expression: exp.StGeogFromGeoJson) -> str:
1161        make_valid = expression.args.get("make_valid")
1162        if make_valid is not None and not isinstance(make_valid, exp.Kwarg):
1163            make_valid = exp.Kwarg(this=exp.var("make_valid"), expression=make_valid)
1164        return self.func(expression.sql_name(), expression.this, make_valid)
1165
1166    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
1167        this = expression.this
1168
1169        # This ensures that inline type-annotated ARRAY literals like ARRAY<INT64>[1, 2, 3]
1170        # are roundtripped unaffected. The inner check excludes ARRAY(SELECT ...) expressions,
1171        # because they aren't literals and so the above syntax is invalid BigQuery.
1172        if isinstance(this, exp.Array):
1173            elem = seq_get(this.expressions, 0)
1174            if not (elem and elem.find(exp.Query)):
1175                return f"{self.sql(expression, 'to')}{self.sql(this)}"
1176
1177        return super().cast_sql(expression, safe_prefix=safe_prefix)
1178
1179    def ordered_sql(self, expression: exp.Ordered) -> str:
1180        order = expression.parent
1181        window = order.parent if isinstance(order, exp.Order) else None
1182        if not isinstance(window, exp.Window) or not _nondefault_null_order(expression):
1183            return super().ordered_sql(expression)
1184
1185        # A WINDOW definition can be used with different functions and frames.
1186        if isinstance(window.this, exp.Identifier):
1187            return super().ordered_sql(expression.copy())
1188
1189        spec = window.args.get("spec")
1190        if not _is_value_window(window) or (spec and spec.text("kind").upper() != "RANGE"):
1191            return super().ordered_sql(expression)
1192
1193        key = expression.this
1194        needs_null_key = key not in (window.args.get("partition_by") or [])
1195        if spec and any(isinstance(spec.args.get(bound), exp.Expr) for bound in ("start", "end")):
1196            # An offset RANGE allows only one key. With finite bounds, NULL keys can
1197            # only frame other NULLs, so their position relative to non-NULLs is immaterial.
1198            if needs_null_key and any(
1199                spec.text(bound).upper() == "UNBOUNDED" for bound in ("start", "end")
1200            ):
1201                return super().ordered_sql(expression)
1202            needs_null_key = False
1203
1204        desc = expression.args.get("desc")
1205        expression = expression.copy()
1206        expression.set("nulls_first", not desc)
1207        sql = super().ordered_sql(expression)
1208        if not needs_null_key:
1209            return sql
1210
1211        if isinstance(key, (exp.Not, exp.Predicate)):
1212            key = exp.paren(key)
1213        is_null = key.is_(exp.null())
1214        return f"{self.sql(is_null)}{' DESC' if desc else ''}, {sql}"
1215
1216    def clusterproperty_sql(self, expression: exp.ClusterProperty) -> str:
1217        if expression.this:
1218            self.unsupported(f"Unsupported CLUSTER BY {self.sql(expression, 'this')}")
1219            return ""
1220        return self.op_expressions("CLUSTER BY", expression)
logger = <Logger sqlglot (WARNING)>
DQUOTES_ESCAPING_JSON_FUNCTIONS = ('JSON_QUERY', 'JSON_VALUE', 'JSON_QUERY_ARRAY')
ZONELESS_TYPES = {<DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, <DType.DATETIME: 'DATETIME'>, <DType.TIMESTAMP: 'TIMESTAMP'>}
ZONED_TYPES = {<DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <DType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>}
DATE_DIFF_DATETIME_UNITS = {'QUARTER', 'ISOWEEK', 'MONTH', 'ISOYEAR', 'WEEK', 'YEAR'}
class BigQueryGenerator(sqlglot.generator.Generator):
 486class BigQueryGenerator(generator.Generator):
 487    TRY_SUPPORTED = False
 488    SUPPORTS_UESCAPE = False
 489    SUPPORTS_DECODE_CASE = False
 490    SUPPORTS_MULTI_ARG_CHR = False
 491    INTERVAL_ALLOWS_PLURAL_FORM = False
 492    JOIN_HINTS = False
 493    QUERY_HINTS = False
 494    TABLE_HINTS = False
 495    LIMIT_FETCH = "LIMIT"
 496    RENAME_TABLE_WITH_DB = False
 497    NVL2_SUPPORTED = False
 498    UNNEST_WITH_ORDINALITY = False
 499    CAST_TO_INT_ROUNDS = True
 500    COLLATE_IS_FUNC = True
 501    LIMIT_ONLY_LITERALS = True
 502    SUPPORTS_TABLE_ALIAS_COLUMNS = False
 503    SUPPORTS_NAMED_CTE_COLUMNS = False
 504    UNPIVOT_ALIASES_ARE_IDENTIFIERS = False
 505    JSON_KEY_VALUE_PAIR_SEP = ","
 506    NULL_ORDERING_SUPPORTED: bool | None = False
 507    IGNORE_NULLS_IN_FUNC = True
 508    JSON_PATH_SINGLE_QUOTE_ESCAPE = True
 509    CAN_IMPLEMENT_ARRAY_ANY = True
 510    SUPPORTS_TO_NUMBER = False
 511    NAMED_PLACEHOLDER_TOKEN = "@"
 512    HEX_FUNC = "TO_HEX"
 513    WITH_PROPERTIES_PREFIX = "OPTIONS"
 514    SUPPORTS_EXPLODING_PROJECTIONS = False
 515    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
 516    SUPPORTS_UNIX_SECONDS = True
 517    DECLARE_DEFAULT_ASSIGNMENT = "DEFAULT"
 518
 519    SAFE_JSON_PATH_KEY_RE = re.compile(r"^[\-\w]*$")
 520
 521    WINDOW_FUNCS_REQUIRING_ORDER = (
 522        exp.CumeDist,
 523        exp.DenseRank,
 524        exp.FirstValue,
 525        exp.LastValue,
 526        exp.NthValue,
 527        exp.Ntile,
 528        exp.PercentRank,
 529        exp.Rank,
 530    )
 531
 532    WINDOW_FUNCS_WITH_NULL_ORDERING = (
 533        exp.CumeDist,
 534        exp.DenseRank,
 535        exp.FirstValue,
 536        exp.Lag,
 537        exp.LastValue,
 538        exp.Lead,
 539        exp.NthValue,
 540        exp.Ntile,
 541        exp.PercentRank,
 542        exp.Rank,
 543        exp.RowNumber,
 544    )
 545
 546    TS_OR_DS_TYPES: t.ClassVar = (
 547        exp.TsOrDsToDatetime,
 548        exp.TsOrDsToTimestamp,
 549        exp.TsOrDsToTime,
 550        exp.TsOrDsToDate,
 551    )
 552
 553    TRANSFORMS = {
 554        **generator.Generator.TRANSFORMS,
 555        exp.AIEmbed: rename_func("EMBED"),
 556        exp.AIGenerate: rename_func("GENERATE"),
 557        exp.AISimilarity: rename_func("SIMILARITY"),
 558        exp.ApproxTopK: rename_func("APPROX_TOP_COUNT"),
 559        exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"),
 560        exp.ArgMax: arg_max_or_min_no_count("MAX_BY"),
 561        exp.ArgMin: arg_max_or_min_no_count("MIN_BY"),
 562        exp.Array: inline_array_unless_query,
 563        exp.ArrayContains: _array_contains_sql,
 564        exp.ArrayDistinct: _array_agg_fold_sql,
 565        exp.ArraySort: _array_agg_fold_sql,
 566        exp.ArrayFilter: filter_array_using_unnest,
 567        exp.ArrayRemove: filter_array_using_unnest,
 568        exp.BitwiseAndAgg: rename_func("BIT_AND"),
 569        exp.BitwiseOrAgg: rename_func("BIT_OR"),
 570        exp.BitwiseXorAgg: rename_func("BIT_XOR"),
 571        exp.BitwiseCount: rename_func("BIT_COUNT"),
 572        exp.ByteLength: rename_func("BYTE_LENGTH"),
 573        exp.Cast: transforms.preprocess(
 574            [_widen_decimal, transforms.remove_precision_parameterized_types]
 575        ),
 576        exp.TryCast: transforms.preprocess(
 577            [_widen_decimal, transforms.remove_precision_parameterized_types]
 578        ),
 579        exp.CollateProperty: lambda self, e: (
 580            f"DEFAULT COLLATE {self.sql(e, 'this')}"
 581            if e.args.get("default")
 582            else f"COLLATE {self.sql(e, 'this')}"
 583        ),
 584        exp.Commit: lambda *_: "COMMIT TRANSACTION",
 585        exp.CountIf: rename_func("COUNTIF"),
 586        exp.Create: _create_sql,
 587        exp.CTE: transforms.preprocess([_pushdown_cte_column_names]),
 588        exp.DateFromParts: rename_func("DATE"),
 589        exp.DateStrToDate: datestrtodate_sql,
 590        exp.DatetimeAdd: date_add_interval_sql("DATETIME", "ADD"),
 591        exp.DatetimeSub: date_add_interval_sql("DATETIME", "SUB"),
 592        exp.DateFromUnixDate: rename_func("DATE_FROM_UNIX_DATE"),
 593        exp.Day: _extract_part("DAY"),
 594        exp.DayOfMonth: _extract_part("DAY"),
 595        exp.DayOfWeekIso: _day_of_week_iso_sql,
 596        exp.DayOfYear: _extract_part("DAYOFYEAR"),
 597        exp.Filter: no_filter_sql,
 598        exp.FromTimeZone: lambda self, e: self.func(
 599            "DATETIME", self.func("TIMESTAMP", e.this, e.args.get("zone")), "'UTC'"
 600        ),
 601        exp.GenerateSeries: generate_series_sql("GENERATE_ARRAY"),
 602        exp.GroupConcat: lambda self, e: groupconcat_sql(
 603            self, e, func_name="STRING_AGG", within_group=False, sep=None
 604        ),
 605        exp.GT: _comparison_sql(">"),
 606        exp.GTE: _comparison_sql(">="),
 607        exp.Hex: lambda self, e: self.func("UPPER", self.func("TO_HEX", self.sql(e, "this"))),
 608        exp.HexString: lambda self, e: self.hexstring_sql(e, binary_function_repr="FROM_HEX"),
 609        exp.Hour: _extract_part("HOUR"),
 610        exp.If: if_sql(false_value="NULL"),
 611        exp.ILike: no_ilike_sql,
 612        exp.IntDiv: rename_func("DIV"),
 613        exp.Int64: rename_func("INT64"),
 614        exp.JSONBool: rename_func("BOOL"),
 615        exp.JSONExtract: _json_extract_sql,
 616        exp.JSONExtractArray: _json_extract_sql,
 617        exp.JSONExtractScalar: _json_extract_sql,
 618        exp.JSONFormat: lambda self, e: self.func(
 619            "TO_JSON" if e.args.get("to_json") else "TO_JSON_STRING",
 620            e.this,
 621            e.args.get("options"),
 622        ),
 623        exp.JSONKeysAtDepth: rename_func("JSON_KEYS"),
 624        exp.JSONValueArray: rename_func("JSON_VALUE_ARRAY"),
 625        exp.Levenshtein: _levenshtein_sql,
 626        exp.LT: _comparison_sql("<"),
 627        exp.LTE: _comparison_sql("<="),
 628        exp.Max: max_or_greatest,
 629        exp.MD5: lambda self, e: self.func("TO_HEX", self.func("MD5", e.this)),
 630        exp.MD5Digest: rename_func("MD5"),
 631        exp.Min: min_or_least,
 632        exp.Month: _extract_part("MONTH"),
 633        exp.NEQ: _comparison_sql("<>"),
 634        exp.Normalize: lambda self, e: self.func(
 635            "NORMALIZE_AND_CASEFOLD" if e.args.get("is_casefold") else "NORMALIZE",
 636            e.this,
 637            e.args.get("form"),
 638        ),
 639        exp.NullSafeEQ: _comparison_sql("IS NOT DISTINCT FROM"),
 640        exp.NullSafeNEQ: _comparison_sql("IS DISTINCT FROM"),
 641        exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
 642        exp.Quarter: _extract_part("QUARTER"),
 643        exp.RegexpExtract: lambda self, e: self.func(
 644            "REGEXP_EXTRACT",
 645            e.this,
 646            e.expression,
 647            e.args.get("position"),
 648            e.args.get("occurrence"),
 649        ),
 650        exp.RegexpExtractAll: lambda self, e: self.func("REGEXP_EXTRACT_ALL", e.this, e.expression),
 651        exp.RegexpReplace: regexp_replace_sql,
 652        exp.RegexpLike: rename_func("REGEXP_CONTAINS"),
 653        exp.ReturnsProperty: _returnsproperty_sql,
 654        exp.Rollback: lambda *_: "ROLLBACK TRANSACTION",
 655        exp.ParseTime: lambda self, e: self.func("PARSE_TIME", self.format_time(e), e.this),
 656        exp.ParseDatetime: lambda self, e: self.func("PARSE_DATETIME", self.format_time(e), e.this),
 657        exp.Select: transforms.preprocess(
 658            [
 659                _unnest_explode_generate_series,
 660                transforms.explode_projection_to_unnest(),
 661                transforms.unqualify_unnest,
 662                transforms.eliminate_distinct_on,
 663                _alias_ordered_group,
 664                lambda e: transforms.eliminate_window_clause(e, _inline_value_window_order),
 665                transforms.eliminate_semi_and_anti_joins,
 666                _add_single_row_source,
 667            ]
 668        ),
 669        exp.SHA: rename_func("SHA1"),
 670        exp.SHA2: sha256_sql,
 671        exp.SHA1Digest: rename_func("SHA1"),
 672        exp.SHA2Digest: sha2_digest_sql,
 673        exp.StabilityProperty: lambda self, e: (
 674            "DETERMINISTIC" if e.name == "IMMUTABLE" else "NOT DETERMINISTIC"
 675        ),
 676        exp.String: rename_func("STRING"),
 677        exp.StrPosition: lambda self, e: strposition_sql(
 678            self, e, func_name="INSTR", supports_position=True, supports_occurrence=True
 679        ),
 680        exp.StrToDate: _str_to_datetime_sql,
 681        exp.StrToTime: _str_to_datetime_sql,
 682        exp.SessionUser: lambda *_: "SESSION_USER()",
 683        exp.Table: transforms.preprocess([transforms.unnest_generate_series]),
 684        exp.TimeAdd: date_add_interval_sql("TIME", "ADD"),
 685        exp.TimeFromParts: rename_func("TIME"),
 686        exp.TimestampFromParts: rename_func("DATETIME"),
 687        exp.TimeSub: date_add_interval_sql("TIME", "SUB"),
 688        exp.TimestampAdd: date_add_interval_sql("TIMESTAMP", "ADD"),
 689        exp.TimestampDiff: lambda self, e: self.func(
 690            "TIMESTAMP_DIFF", e.this, e.expression, e.unit
 691        ),
 692        exp.TimestampSub: date_add_interval_sql("TIMESTAMP", "SUB"),
 693        exp.TimeStrToTime: timestrtotime_sql,
 694        exp.Transaction: lambda *_: "BEGIN TRANSACTION",
 695        exp.TsOrDsAdd: _ts_or_ds_add_sql,
 696        exp.TsOrDsDiff: _ts_or_ds_diff_sql,
 697        exp.TsOrDsToTime: rename_func("TIME"),
 698        exp.TsOrDsToDatetime: rename_func("DATETIME"),
 699        exp.TsOrDsToTimestamp: rename_func("TIMESTAMP"),
 700        exp.Unhex: rename_func("FROM_HEX"),
 701        exp.UnixDate: rename_func("UNIX_DATE"),
 702        exp.UnixToTime: _unix_to_time_sql,
 703        exp.Uuid: lambda *_: "GENERATE_UUID()",
 704        exp.Values: _derived_table_values_to_unnest,
 705        exp.VariancePop: rename_func("VAR_POP"),
 706        exp.WeekOfYear: _extract_part("ISOWEEK"),
 707        exp.Year: _extract_part("YEAR"),
 708        exp.SafeDivide: rename_func("SAFE_DIVIDE"),
 709    }
 710
 711    SUPPORTED_JSON_PATH_PARTS = {
 712        exp.JSONPathKey,
 713        exp.JSONPathRoot,
 714        exp.JSONPathSubscript,
 715    }
 716
 717    TYPE_MAPPING = {
 718        **generator.Generator.TYPE_MAPPING,
 719        exp.DType.BIGDECIMAL: "BIGNUMERIC",
 720        exp.DType.BIGINT: "INT64",
 721        exp.DType.BINARY: "BYTES",
 722        exp.DType.BLOB: "BYTES",
 723        exp.DType.BOOLEAN: "BOOL",
 724        exp.DType.CHAR: "STRING",
 725        exp.DType.DECIMAL: "NUMERIC",
 726        exp.DType.DOUBLE: "FLOAT64",
 727        exp.DType.FLOAT: "FLOAT64",
 728        exp.DType.INT: "INT64",
 729        exp.DType.NCHAR: "STRING",
 730        exp.DType.NVARCHAR: "STRING",
 731        exp.DType.SMALLINT: "INT64",
 732        exp.DType.TEXT: "STRING",
 733        exp.DType.TIMESTAMP: "DATETIME",
 734        exp.DType.TIMESTAMPNTZ: "DATETIME",
 735        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
 736        exp.DType.TIMESTAMPLTZ: "TIMESTAMP",
 737        exp.DType.TINYINT: "INT64",
 738        exp.DType.ROWVERSION: "BYTES",
 739        exp.DType.UUID: "STRING",
 740        exp.DType.VARBINARY: "BYTES",
 741        exp.DType.VARCHAR: "STRING",
 742        exp.DType.VARIANT: "ANY TYPE",
 743    }
 744
 745    PROPERTIES_LOCATION = {
 746        **generator.Generator.PROPERTIES_LOCATION,
 747        exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
 748        exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
 749    }
 750
 751    # WINDOW comes after QUALIFY
 752    # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#window_clause
 753    # BigQuery requires QUALIFY before WINDOW
 754    AFTER_HAVING_MODIFIER_TRANSFORMS = {
 755        "qualify": generator.AFTER_HAVING_MODIFIER_TRANSFORMS["qualify"],
 756        "windows": generator.AFTER_HAVING_MODIFIER_TRANSFORMS["windows"],
 757    }
 758
 759    # from: https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#reserved_keywords
 760    RESERVED_KEYWORDS = {
 761        "all",
 762        "and",
 763        "any",
 764        "array",
 765        "as",
 766        "asc",
 767        "assert_rows_modified",
 768        "at",
 769        "between",
 770        "by",
 771        "case",
 772        "cast",
 773        "collate",
 774        "contains",
 775        "create",
 776        "cross",
 777        "cube",
 778        "current",
 779        "default",
 780        "define",
 781        "desc",
 782        "distinct",
 783        "else",
 784        "end",
 785        "enum",
 786        "escape",
 787        "except",
 788        "exclude",
 789        "exists",
 790        "extract",
 791        "false",
 792        "fetch",
 793        "following",
 794        "for",
 795        "from",
 796        "full",
 797        "group",
 798        "grouping",
 799        "groups",
 800        "hash",
 801        "having",
 802        "if",
 803        "ignore",
 804        "in",
 805        "inner",
 806        "intersect",
 807        "interval",
 808        "into",
 809        "is",
 810        "join",
 811        "lateral",
 812        "left",
 813        "like",
 814        "limit",
 815        "lookup",
 816        "merge",
 817        "natural",
 818        "new",
 819        "no",
 820        "not",
 821        "null",
 822        "nulls",
 823        "of",
 824        "on",
 825        "or",
 826        "order",
 827        "outer",
 828        "over",
 829        "partition",
 830        "preceding",
 831        "proto",
 832        "qualify",
 833        "range",
 834        "recursive",
 835        "respect",
 836        "right",
 837        "rollup",
 838        "rows",
 839        "select",
 840        "set",
 841        "some",
 842        "struct",
 843        "tablesample",
 844        "then",
 845        "to",
 846        "treat",
 847        "true",
 848        "unbounded",
 849        "union",
 850        "unnest",
 851        "using",
 852        "when",
 853        "where",
 854        "window",
 855        "with",
 856        "within",
 857    }
 858
 859    def __init__(
 860        self,
 861        pretty: bool | int | None = None,
 862        identify: str | bool = False,
 863        normalize: bool = False,
 864        pad: int = 2,
 865        indent: int = 2,
 866        normalize_functions: str | bool | None = None,
 867        unsupported_level: ErrorLevel = ErrorLevel.WARN,
 868        max_unsupported: int = 3,
 869        leading_comma: bool = False,
 870        max_text_width: int = 80,
 871        comments: bool = True,
 872        dialect: DialectType = None,
 873    ) -> None:
 874        super().__init__(
 875            pretty=pretty,
 876            identify=identify,
 877            normalize=normalize,
 878            pad=pad,
 879            indent=indent,
 880            normalize_functions=normalize_functions,
 881            unsupported_level=unsupported_level,
 882            max_unsupported=max_unsupported,
 883            leading_comma=leading_comma,
 884            max_text_width=max_text_width,
 885            comments=comments,
 886            dialect=dialect,
 887        )
 888
 889        self._escaped_identifier_end = r"\`"
 890
 891        # Escape existing backslashes before introducing new escape sequences.
 892        self._identifier_escaped_sequences = {
 893            **self._identifier_escaped_sequences,
 894            **self.dialect.ESCAPED_SEQUENCES,
 895        }
 896
 897    def frombase_sql(self, expression: exp.FromBase) -> str:
 898        # Hex is the only base BigQuery can cast from, and the sign goes before the prefix, e.g. -0xff
 899        if expression.expression.name != "16":
 900            self.unsupported("FROM_BASE is only supported for base 16")
 901            return self.function_fallback_sql(expression)
 902
 903        prefixed = exp.func(
 904            "REGEXP_REPLACE",
 905            expression.this,
 906            exp.Literal.string("^([+-]?)"),
 907            exp.Literal.string("\\10x"),
 908            copy=False,
 909        )
 910        return self.sql(exp.cast(prefixed, exp.DType.BIGINT, copy=False))
 911
 912    def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str:
 913        node: exp.Expr = expression
 914        while node.parent and not isinstance(node.parent, (exp.Window, exp.AggFunc, exp.Select)):
 915            node = node.parent
 916        if isinstance(node.parent, exp.Window) and node.arg_key == "this":
 917            self.unsupported("APPROX_QUANTILES does not support window functions")
 918            return self.function_fallback_sql(expression)
 919
 920        # The k/n quantile is APPROX_QUANTILES(x, n)[k], e.g. 0.95 -> n = 20, k = 19. n is at most
 921        # 100,000, so the quantile has at most 5 decimal places, and Decimal comparisons are exact
 922        quantile = expression.args["quantile"]
 923        weight = expression.args.get("weight")
 924        value = Decimal(quantile.to_py()) if quantile.is_number else None
 925        if (
 926            value is None
 927            or not 0 <= value <= 1
 928            or round(value, 5) != value
 929            or (weight and (not weight.is_number or weight.to_py() != 1))
 930        ):
 931            self.unsupported("APPROX_QUANTILE needs a literal quantile and no weight")
 932            return self.function_fallback_sql(expression)
 933
 934        fraction = Fraction(value)
 935        quantiles = exp.func("APPROX_QUANTILES", expression.this, fraction.denominator, copy=False)
 936        return self.sql(quantiles[fraction.numerator])
 937
 938    def weekstart_sql(self, expression: exp.WeekStart) -> str:
 939        if expression.this.name.upper() == "SUNDAY":
 940            # BigQuery specific optimization since WEEK(SUNDAY) == WEEK
 941            return "WEEK"
 942
 943        return self.func("WEEK", expression.this)
 944
 945    def dateadd_sql(self, expression: exp.DateAdd | exp.DateSub) -> str:
 946        kind = "SUB" if isinstance(expression, exp.DateSub) else "ADD"
 947        this = expression.this
 948        if expression.text("unit") in ("WEEK", "MONTH", "QUARTER", "YEAR") and _is_timestamp(this):
 949            # TIMESTAMP arithmetic only takes units up to DAY, so use the UTC DATETIME instead
 950            shifted = (exp.DatetimeSub if kind == "SUB" else exp.DatetimeAdd)(
 951                this=exp.TsOrDsToDatetime(this=this),
 952                expression=expression.expression,
 953                unit=expression.unit,
 954            )
 955            return self.func("TIMESTAMP", shifted)
 956
 957        return date_add_interval_sql("DATE", kind)(self, expression)
 958
 959    def datesub_sql(self, expression: exp.DateSub) -> str:
 960        return self.dateadd_sql(expression)
 961
 962    def datediff_sql(self, expression: exp.DateDiff) -> str:
 963        this = expression.this
 964        expr = expression.expression
 965        unit = expression.text("unit")
 966        if not isinstance(expression.unit, exp.WeekStart) and unit not in DATE_DIFF_DATETIME_UNITS:
 967            return self.func("DATE_DIFF", this, expr, unit_to_var(expression))
 968
 969        zoned_types = (exp.DType.TIMESTAMPTZ, exp.DType.TIMESTAMPLTZ)
 970        zoned = this.unnest().is_type(*zoned_types) or expr.unnest().is_type(*zoned_types)
 971        if zoned:
 972            self.unsupported("DATE_DIFF reads TIMESTAMP WITH TIME ZONE values in UTC")
 973
 974        if unit == "WEEK" and not expression.args.get("date_part_boundary"):
 975            self.unsupported("DATE_DIFF counts the Sundays crossed, not whole weeks")
 976
 977        if not zoned and not (_is_timestamp(this) or _is_timestamp(expr)):
 978            return self.func("DATE_DIFF", this, expr, unit_to_var(expression))
 979
 980        # These units only take DATE or DATETIME operands, so both sides are cast to DATETIME,
 981        # which reads a TIMESTAMP in UTC
 982        return self.func(
 983            "DATE_DIFF",
 984            _datetime_operand(this, self.dialect),
 985            _datetime_operand(expr, self.dialect),
 986            unit_to_var(expression),
 987        )
 988
 989    def datetrunc_sql(self, expression: exp.DateTrunc) -> str:
 990        self._warn_unsupported_arg(expression, "century_from_zero")
 991        unit = expression.unit
 992        if unit.is_string and unit.name.upper() in ("WEEK_OF_MONTH", "WEEK_OF_YEAR"):
 993            self.unsupported(f"Unexpected interval unit: {unit.name}")
 994        unit_sql = unit.name if unit.is_string else self.sql(unit)
 995        return self.func("DATE_TRUNC", expression.this, unit_sql, expression.args.get("zone"))
 996
 997    def mod_sql(self, expression: exp.Mod) -> str:
 998        self.nullif_zero_divisor(expression)
 999        this = expression.this
1000        expr = expression.expression
1001        return self.func(
1002            "MOD",
1003            this.unnest() if isinstance(this, exp.Paren) else this,
1004            expr.unnest() if isinstance(expr, exp.Paren) else expr,
1005        )
1006
1007    def column_parts(self, expression: exp.Column) -> str:
1008        if expression.meta_get("quoted_column"):
1009            # If a column reference is of the form `dataset.table`.name, we need
1010            # to preserve the quoted table path, otherwise the reference breaks
1011            table_parts = ".".join(p.name for p in expression.parts[:-1])
1012            table_path = self.sql(exp.Identifier(this=table_parts, quoted=True))
1013            return f"{table_path}.{self.sql(expression, 'this')}"
1014
1015        return super().column_parts(expression)
1016
1017    def table_parts(self, expression: exp.Table) -> str:
1018        # Depending on the context, `x.y` may not resolve to the same data source as `x`.`y`, so
1019        # we need to make sure the correct quoting is used in each case.
1020        #
1021        # For example, if there is a CTE x that clashes with a schema name, then the former will
1022        # return the table y in that schema, whereas the latter will return the CTE's y column:
1023        #
1024        # - WITH x AS (SELECT [1, 2] AS y) SELECT * FROM x, `x.y`   -> cross join
1025        # - WITH x AS (SELECT [1, 2] AS y) SELECT * FROM x, `x`.`y` -> implicit unnest
1026        if expression.meta_get("quoted_table"):
1027            table_parts = ".".join(p.name for p in expression.parts)
1028            return self.sql(exp.Identifier(this=table_parts, quoted=True))
1029
1030        return super().table_parts(expression)
1031
1032    def timetostr_sql(self, expression: exp.TimeToStr) -> str:
1033        this = expression.this
1034        if isinstance(this, exp.TsOrDsToDatetime):
1035            func_name = "FORMAT_DATETIME"
1036        elif isinstance(this, exp.TsOrDsToTimestamp):
1037            func_name = "FORMAT_TIMESTAMP"
1038        elif isinstance(this, exp.TsOrDsToTime):
1039            func_name = "FORMAT_TIME"
1040        else:
1041            func_name = "FORMAT_DATE"
1042
1043        time_expr = this if isinstance(this, self.TS_OR_DS_TYPES) else expression
1044        return self.func(
1045            func_name, self.format_time(expression), time_expr.this, expression.args.get("zone")
1046        )
1047
1048    def eq_sql(self, expression: exp.EQ) -> str:
1049        # Operands of = cannot be NULL in BigQuery
1050        if isinstance(expression.left, exp.Null) or isinstance(expression.right, exp.Null):
1051            if not isinstance(expression.parent, exp.Update):
1052                return "NULL"
1053
1054        _cast_zoneless_operand(expression)
1055        return self.binary(expression, "=")
1056
1057    def escape_sql(self, expression: exp.Escape) -> str:
1058        # BigQuery's LIKE has no ESCAPE clause and always escapes with a backslash, so a literal
1059        # pattern is rewritten to backslash escapes. UPPER/LOWER around it can't change a
1060        # caseless escape character, e.g. ^, so those patterns are rewritten too.
1061        like, char = expression.this.copy(), expression.expression.name
1062        pattern = like.expression
1063        if isinstance(pattern, (exp.Upper, exp.Lower)) and char.upper() == char.lower():
1064            pattern = pattern.this
1065        e = re.escape(char)
1066        if not (
1067            isinstance(like, exp.Like)
1068            and expression.expression.is_string
1069            and len(char) == 1
1070            and pattern.is_string
1071            and re.fullmatch(f"(?:[^{e}]|{e}[%_{e}])*", pattern.name)
1072        ):
1073            return super().escape_sql(expression)
1074
1075        # Escaped %, _ and backslash, and unescaped backslash, get a backslash
1076        pattern.set(
1077            "this",
1078            re.sub(
1079                f"{e}[%_{e}]|\\\\",
1080                lambda m: "\\" * (m[0][-1] in "%_\\") + m[0][-1],
1081                pattern.name,
1082            ),
1083        )
1084        return self.sql(like)
1085
1086    def _native_dayofweek_sql(self, expression: exp.DayOfWeek) -> str:
1087        return self.sql(exp.Extract(this=exp.var("DAYOFWEEK"), expression=expression.this))
1088
1089    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
1090        parent = expression.parent
1091
1092        # BigQuery allows CAST(.. AS {STRING|TIMESTAMP} [FORMAT <fmt> [AT TIME ZONE <tz>]]).
1093        # Only the TIMESTAMP one should use the below conversion, when AT TIME ZONE is included.
1094        if not isinstance(parent, exp.Cast) or not parent.to.is_type("text"):
1095            this = expression.this
1096            if expression.args.get("session_zone"):
1097                # DATETIME(<ts>, <zone>) only accepts a TIMESTAMP and BigQuery reads a DATETIME
1098                # cast to TIMESTAMP as UTC, so this assumes the source session time zone is UTC
1099                this = exp.cast(this, exp.DType.TIMESTAMPTZ)
1100
1101            return self.func("TIMESTAMP", self.func("DATETIME", this, expression.args.get("zone")))
1102
1103        return super().attimezone_sql(expression)
1104
1105    def trycast_sql(self, expression: exp.TryCast) -> str:
1106        return self.cast_sql(expression, safe_prefix="SAFE_")
1107
1108    def bracket_sql(self, expression: exp.Bracket) -> str:
1109        this = expression.this
1110        expressions = expression.expressions
1111
1112        if len(expressions) == 1 and this and this.is_type(exp.DType.STRUCT):
1113            arg = expressions[0]
1114            if arg.type is None:
1115                from sqlglot.optimizer.annotate_types import annotate_types
1116
1117                arg = annotate_types(arg, dialect=self.dialect)
1118
1119            if arg.type and arg.type.this in exp.DataType.TEXT_TYPES:
1120                # BQ doesn't support bracket syntax with string values for structs
1121                return f"{self.sql(this)}.{arg.name}"
1122
1123        expressions_sql = self.expressions(expression, flat=True)
1124        offset = expression.args.get("offset")
1125
1126        if offset == 0:
1127            expressions_sql = f"OFFSET({expressions_sql})"
1128        elif offset == 1:
1129            expressions_sql = f"ORDINAL({expressions_sql})"
1130        elif offset is not None:
1131            self.unsupported(f"Unsupported array offset: {offset}")
1132
1133        if expression.args.get("safe"):
1134            expressions_sql = f"SAFE_{expressions_sql}"
1135
1136        return f"{self.sql(this)}[{expressions_sql}]"
1137
1138    def in_unnest_op(self, expression: exp.Unnest) -> str:
1139        return self.sql(expression)
1140
1141    def version_sql(self, expression: exp.Version) -> str:
1142        if expression.name == "TIMESTAMP":
1143            expression.set("this", "SYSTEM_TIME")
1144        return super().version_sql(expression)
1145
1146    def contains_sql(self, expression: exp.Contains) -> str:
1147        this = expression.this
1148        expr = expression.expression
1149
1150        if isinstance(this, exp.Lower) and isinstance(expr, exp.Lower):
1151            this = this.this
1152            expr = expr.this
1153
1154        return self.func("CONTAINS_SUBSTR", this, expr, expression.args.get("json_scope"))
1155
1156    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
1157        if expression.args.get("is_literal"):
1158            return f"JSON {self.sql(expression, 'this')}"
1159        return super().parsejson_sql(expression)
1160
1161    def stgeogfromgeojson_sql(self, expression: exp.StGeogFromGeoJson) -> str:
1162        make_valid = expression.args.get("make_valid")
1163        if make_valid is not None and not isinstance(make_valid, exp.Kwarg):
1164            make_valid = exp.Kwarg(this=exp.var("make_valid"), expression=make_valid)
1165        return self.func(expression.sql_name(), expression.this, make_valid)
1166
1167    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
1168        this = expression.this
1169
1170        # This ensures that inline type-annotated ARRAY literals like ARRAY<INT64>[1, 2, 3]
1171        # are roundtripped unaffected. The inner check excludes ARRAY(SELECT ...) expressions,
1172        # because they aren't literals and so the above syntax is invalid BigQuery.
1173        if isinstance(this, exp.Array):
1174            elem = seq_get(this.expressions, 0)
1175            if not (elem and elem.find(exp.Query)):
1176                return f"{self.sql(expression, 'to')}{self.sql(this)}"
1177
1178        return super().cast_sql(expression, safe_prefix=safe_prefix)
1179
1180    def ordered_sql(self, expression: exp.Ordered) -> str:
1181        order = expression.parent
1182        window = order.parent if isinstance(order, exp.Order) else None
1183        if not isinstance(window, exp.Window) or not _nondefault_null_order(expression):
1184            return super().ordered_sql(expression)
1185
1186        # A WINDOW definition can be used with different functions and frames.
1187        if isinstance(window.this, exp.Identifier):
1188            return super().ordered_sql(expression.copy())
1189
1190        spec = window.args.get("spec")
1191        if not _is_value_window(window) or (spec and spec.text("kind").upper() != "RANGE"):
1192            return super().ordered_sql(expression)
1193
1194        key = expression.this
1195        needs_null_key = key not in (window.args.get("partition_by") or [])
1196        if spec and any(isinstance(spec.args.get(bound), exp.Expr) for bound in ("start", "end")):
1197            # An offset RANGE allows only one key. With finite bounds, NULL keys can
1198            # only frame other NULLs, so their position relative to non-NULLs is immaterial.
1199            if needs_null_key and any(
1200                spec.text(bound).upper() == "UNBOUNDED" for bound in ("start", "end")
1201            ):
1202                return super().ordered_sql(expression)
1203            needs_null_key = False
1204
1205        desc = expression.args.get("desc")
1206        expression = expression.copy()
1207        expression.set("nulls_first", not desc)
1208        sql = super().ordered_sql(expression)
1209        if not needs_null_key:
1210            return sql
1211
1212        if isinstance(key, (exp.Not, exp.Predicate)):
1213            key = exp.paren(key)
1214        is_null = key.is_(exp.null())
1215        return f"{self.sql(is_null)}{' DESC' if desc else ''}, {sql}"
1216
1217    def clusterproperty_sql(self, expression: exp.ClusterProperty) -> str:
1218        if expression.this:
1219            self.unsupported(f"Unsupported CLUSTER BY {self.sql(expression, 'this')}")
1220            return ""
1221        return self.op_expressions("CLUSTER BY", 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
BigQueryGenerator( pretty: bool | int | None = None, identify: str | bool = False, normalize: bool = False, pad: int = 2, indent: int = 2, normalize_functions: str | bool | None = None, unsupported_level: sqlglot.errors.ErrorLevel = <ErrorLevel.WARN: 'WARN'>, max_unsupported: int = 3, leading_comma: bool = False, max_text_width: int = 80, comments: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None)
859    def __init__(
860        self,
861        pretty: bool | int | None = None,
862        identify: str | bool = False,
863        normalize: bool = False,
864        pad: int = 2,
865        indent: int = 2,
866        normalize_functions: str | bool | None = None,
867        unsupported_level: ErrorLevel = ErrorLevel.WARN,
868        max_unsupported: int = 3,
869        leading_comma: bool = False,
870        max_text_width: int = 80,
871        comments: bool = True,
872        dialect: DialectType = None,
873    ) -> None:
874        super().__init__(
875            pretty=pretty,
876            identify=identify,
877            normalize=normalize,
878            pad=pad,
879            indent=indent,
880            normalize_functions=normalize_functions,
881            unsupported_level=unsupported_level,
882            max_unsupported=max_unsupported,
883            leading_comma=leading_comma,
884            max_text_width=max_text_width,
885            comments=comments,
886            dialect=dialect,
887        )
888
889        self._escaped_identifier_end = r"\`"
890
891        # Escape existing backslashes before introducing new escape sequences.
892        self._identifier_escaped_sequences = {
893            **self._identifier_escaped_sequences,
894            **self.dialect.ESCAPED_SEQUENCES,
895        }
TRY_SUPPORTED = False
SUPPORTS_UESCAPE = False
SUPPORTS_DECODE_CASE = False
SUPPORTS_MULTI_ARG_CHR = False
INTERVAL_ALLOWS_PLURAL_FORM = False
JOIN_HINTS = False
QUERY_HINTS = False
TABLE_HINTS = False
LIMIT_FETCH = 'LIMIT'
RENAME_TABLE_WITH_DB = False
NVL2_SUPPORTED = False
UNNEST_WITH_ORDINALITY = False
CAST_TO_INT_ROUNDS = True
COLLATE_IS_FUNC = True
LIMIT_ONLY_LITERALS = True
SUPPORTS_TABLE_ALIAS_COLUMNS = False
SUPPORTS_NAMED_CTE_COLUMNS = False
UNPIVOT_ALIASES_ARE_IDENTIFIERS = False
JSON_KEY_VALUE_PAIR_SEP = ','
NULL_ORDERING_SUPPORTED: bool | None = False
IGNORE_NULLS_IN_FUNC = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = True
CAN_IMPLEMENT_ARRAY_ANY = True
SUPPORTS_TO_NUMBER = False
NAMED_PLACEHOLDER_TOKEN = '@'
HEX_FUNC = 'TO_HEX'
WITH_PROPERTIES_PREFIX = 'OPTIONS'
SUPPORTS_EXPLODING_PROJECTIONS = False
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
SUPPORTS_UNIX_SECONDS = True
DECLARE_DEFAULT_ASSIGNMENT = 'DEFAULT'
SAFE_JSON_PATH_KEY_RE = re.compile('^[\\-\\w]*$')
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 Generator.<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 BigQueryGenerator.<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 rename_func.<locals>.<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.ReturnsProperty'>: <function _returnsproperty_sql>, <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 BigQueryGenerator.<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 Generator.<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.functions.AIEmbed'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.AIGenerate'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.AISimilarity'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ApproxTopK'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.ApproxDistinct'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ArgMax'>: <function arg_max_or_min_no_count.<locals>._arg_max_or_min_sql>, <class 'sqlglot.expressions.aggregate.ArgMin'>: <function arg_max_or_min_no_count.<locals>._arg_max_or_min_sql>, <class 'sqlglot.expressions.array.Array'>: <function inline_array_unless_query>, <class 'sqlglot.expressions.array.ArrayContains'>: <function _array_contains_sql>, <class 'sqlglot.expressions.array.ArrayDistinct'>: <function _array_agg_fold_sql>, <class 'sqlglot.expressions.array.ArraySort'>: <function _array_agg_fold_sql>, <class 'sqlglot.expressions.array.ArrayFilter'>: <function filter_array_using_unnest>, <class 'sqlglot.expressions.array.ArrayRemove'>: <function filter_array_using_unnest>, <class 'sqlglot.expressions.math.BitwiseAndAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseOrAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseXorAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseCount'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.ByteLength'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.Cast'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.functions.TryCast'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.properties.CollateProperty'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.ddl.Commit'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.CountIf'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.ddl.Create'>: <function _create_sql>, <class 'sqlglot.expressions.query.CTE'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.temporal.DateFromParts'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.temporal.DatetimeAdd'>: <function date_add_interval_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.DatetimeSub'>: <function date_add_interval_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.DateFromUnixDate'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.Day'>: <function _extract_part.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DayOfMonth'>: <function _extract_part.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DayOfWeekIso'>: <function _day_of_week_iso_sql>, <class 'sqlglot.expressions.temporal.DayOfYear'>: <function _extract_part.<locals>.<lambda>>, <class 'sqlglot.expressions.core.Filter'>: <function no_filter_sql>, <class 'sqlglot.expressions.core.FromTimeZone'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.array.GenerateSeries'>: <function generate_series_sql.<locals>._generate_series_sql>, <class 'sqlglot.expressions.aggregate.GroupConcat'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.core.GT'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.core.GTE'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.string.Hex'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.query.HexString'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Hour'>: <function _extract_part.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.If'>: <function if_sql.<locals>._if_sql>, <class 'sqlglot.expressions.core.ILike'>: <function no_ilike_sql>, <class 'sqlglot.expressions.core.IntDiv'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.json.JSONBool'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.json.JSONExtract'>: <function _json_extract_sql>, <class 'sqlglot.expressions.json.JSONExtractArray'>: <function _json_extract_sql>, <class 'sqlglot.expressions.json.JSONExtractScalar'>: <function _json_extract_sql>, <class 'sqlglot.expressions.json.JSONFormat'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONKeysAtDepth'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.JSONValueArray'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Levenshtein'>: <function _levenshtein_sql>, <class 'sqlglot.expressions.core.LT'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.core.LTE'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.aggregate.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.string.MD5'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.string.MD5Digest'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.Min'>: <function min_or_least>, <class 'sqlglot.expressions.temporal.Month'>: <function _extract_part.<locals>.<lambda>>, <class 'sqlglot.expressions.core.NEQ'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.string.Normalize'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.core.NullSafeEQ'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.core.NullSafeNEQ'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Quarter'>: <function _extract_part.<locals>.<lambda>>, <class 'sqlglot.expressions.string.RegexpExtract'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.string.RegexpExtractAll'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.string.RegexpReplace'>: <function regexp_replace_sql>, <class 'sqlglot.expressions.core.RegexpLike'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.ddl.Rollback'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.ParseTime'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.ParseDatetime'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.query.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.SHA'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.SHA2'>: <function sha256_sql>, <class 'sqlglot.expressions.string.SHA1Digest'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.SHA2Digest'>: <function sha2_digest_sql>, <class 'sqlglot.expressions.string.String'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.StrPosition'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.StrToDate'>: <function _str_to_datetime_sql>, <class 'sqlglot.expressions.temporal.StrToTime'>: <function _str_to_datetime_sql>, <class 'sqlglot.expressions.query.Table'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.temporal.TimeAdd'>: <function date_add_interval_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.TimeFromParts'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.TimestampFromParts'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.TimeSub'>: <function date_add_interval_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.TimestampAdd'>: <function date_add_interval_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.TimestampDiff'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimestampSub'>: <function date_add_interval_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.TimeStrToTime'>: <function timestrtotime_sql>, <class 'sqlglot.expressions.ddl.Transaction'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDsAdd'>: <function _ts_or_ds_add_sql>, <class 'sqlglot.expressions.temporal.TsOrDsDiff'>: <function _ts_or_ds_diff_sql>, <class 'sqlglot.expressions.temporal.TsOrDsToTime'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDsToDatetime'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDsToTimestamp'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Unhex'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.UnixDate'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.UnixToTime'>: <function _unix_to_time_sql>, <class 'sqlglot.expressions.functions.Uuid'>: <function BigQueryGenerator.<lambda>>, <class 'sqlglot.expressions.query.Values'>: <function _derived_table_values_to_unnest>, <class 'sqlglot.expressions.aggregate.VariancePop'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.WeekOfYear'>: <function _extract_part.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.Year'>: <function _extract_part.<locals>.<lambda>>, <class 'sqlglot.expressions.math.SafeDivide'>: <function rename_func.<locals>.<lambda>>}
TYPE_MAPPING = {<DType.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <DType.NCHAR: 'NCHAR'>: 'STRING', <DType.NVARCHAR: 'NVARCHAR'>: 'STRING', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <DType.LONGTEXT: 'LONGTEXT'>: 'TEXT', <DType.TINYTEXT: 'TINYTEXT'>: 'TEXT', <DType.BLOB: 'BLOB'>: 'BYTES', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <DType.LONGBLOB: 'LONGBLOB'>: 'BLOB', <DType.TINYBLOB: 'TINYBLOB'>: 'BLOB', <DType.INET: 'INET'>: 'INET', <DType.ROWVERSION: 'ROWVERSION'>: 'BYTES', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP', <DType.BIGDECIMAL: 'BIGDECIMAL'>: 'BIGNUMERIC', <DType.BIGINT: 'BIGINT'>: 'INT64', <DType.BINARY: 'BINARY'>: 'BYTES', <DType.BOOLEAN: 'BOOLEAN'>: 'BOOL', <DType.CHAR: 'CHAR'>: 'STRING', <DType.DECIMAL: 'DECIMAL'>: 'NUMERIC', <DType.DOUBLE: 'DOUBLE'>: 'FLOAT64', <DType.FLOAT: 'FLOAT'>: 'FLOAT64', <DType.INT: 'INT'>: 'INT64', <DType.SMALLINT: 'SMALLINT'>: 'INT64', <DType.TEXT: 'TEXT'>: 'STRING', <DType.TIMESTAMP: 'TIMESTAMP'>: 'DATETIME', <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>: 'DATETIME', <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'TIMESTAMP', <DType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>: 'TIMESTAMP', <DType.TINYINT: 'TINYINT'>: 'INT64', <DType.UUID: 'UUID'>: 'STRING', <DType.VARBINARY: 'VARBINARY'>: 'BYTES', <DType.VARCHAR: 'VARCHAR'>: 'STRING', <DType.VARIANT: 'VARIANT'>: 'ANY TYPE'}
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_SCHEMA: 'POST_SCHEMA'>, <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'>}
AFTER_HAVING_MODIFIER_TRANSFORMS = {'qualify': <function <lambda>>, 'windows': <function <lambda>>}
RESERVED_KEYWORDS = {'all', 'for', 'merge', 'union', 'then', 'at', 'following', 'enum', 'some', 'limit', 'define', 'desc', 'where', 'struct', 'set', 'full', 'exclude', 'to', 'using', 'escape', 'or', 'intersect', 'exists', 'from', 'in', 'join', 'when', 'collate', 'is', 'tablesample', 'unbounded', 'outer', 'end', 'recursive', 'inner', 'any', 'fetch', 'as', 'distinct', 'rows', 'cross', 'nulls', 'within', 'preceding', 'natural', 'select', 'order', 'null', 'asc', 'respect', 'lookup', 'cast', 'cube', 'true', 'hash', 'contains', 'on', 'like', 'window', 'proto', 'ignore', 'unnest', 'and', 'extract', 'else', 'assert_rows_modified', 'right', 'of', 'case', 'no', 'by', 'between', 'not', 'having', 'group', 'except', 'grouping', 'qualify', 'into', 'if', 'current', 'false', 'new', 'interval', 'create', 'over', 'left', 'rollup', 'partition', 'lateral', 'range', 'treat', 'array', 'with', 'default', 'groups'}
def frombase_sql(self, expression: sqlglot.expressions.string.FromBase) -> str:
897    def frombase_sql(self, expression: exp.FromBase) -> str:
898        # Hex is the only base BigQuery can cast from, and the sign goes before the prefix, e.g. -0xff
899        if expression.expression.name != "16":
900            self.unsupported("FROM_BASE is only supported for base 16")
901            return self.function_fallback_sql(expression)
902
903        prefixed = exp.func(
904            "REGEXP_REPLACE",
905            expression.this,
906            exp.Literal.string("^([+-]?)"),
907            exp.Literal.string("\\10x"),
908            copy=False,
909        )
910        return self.sql(exp.cast(prefixed, exp.DType.BIGINT, copy=False))
def approxquantile_sql(self, expression: sqlglot.expressions.aggregate.ApproxQuantile) -> str:
912    def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str:
913        node: exp.Expr = expression
914        while node.parent and not isinstance(node.parent, (exp.Window, exp.AggFunc, exp.Select)):
915            node = node.parent
916        if isinstance(node.parent, exp.Window) and node.arg_key == "this":
917            self.unsupported("APPROX_QUANTILES does not support window functions")
918            return self.function_fallback_sql(expression)
919
920        # The k/n quantile is APPROX_QUANTILES(x, n)[k], e.g. 0.95 -> n = 20, k = 19. n is at most
921        # 100,000, so the quantile has at most 5 decimal places, and Decimal comparisons are exact
922        quantile = expression.args["quantile"]
923        weight = expression.args.get("weight")
924        value = Decimal(quantile.to_py()) if quantile.is_number else None
925        if (
926            value is None
927            or not 0 <= value <= 1
928            or round(value, 5) != value
929            or (weight and (not weight.is_number or weight.to_py() != 1))
930        ):
931            self.unsupported("APPROX_QUANTILE needs a literal quantile and no weight")
932            return self.function_fallback_sql(expression)
933
934        fraction = Fraction(value)
935        quantiles = exp.func("APPROX_QUANTILES", expression.this, fraction.denominator, copy=False)
936        return self.sql(quantiles[fraction.numerator])
def weekstart_sql(self, expression: sqlglot.expressions.functions.WeekStart) -> str:
938    def weekstart_sql(self, expression: exp.WeekStart) -> str:
939        if expression.this.name.upper() == "SUNDAY":
940            # BigQuery specific optimization since WEEK(SUNDAY) == WEEK
941            return "WEEK"
942
943        return self.func("WEEK", expression.this)
def dateadd_sql( self, expression: sqlglot.expressions.temporal.DateAdd | sqlglot.expressions.temporal.DateSub) -> str:
945    def dateadd_sql(self, expression: exp.DateAdd | exp.DateSub) -> str:
946        kind = "SUB" if isinstance(expression, exp.DateSub) else "ADD"
947        this = expression.this
948        if expression.text("unit") in ("WEEK", "MONTH", "QUARTER", "YEAR") and _is_timestamp(this):
949            # TIMESTAMP arithmetic only takes units up to DAY, so use the UTC DATETIME instead
950            shifted = (exp.DatetimeSub if kind == "SUB" else exp.DatetimeAdd)(
951                this=exp.TsOrDsToDatetime(this=this),
952                expression=expression.expression,
953                unit=expression.unit,
954            )
955            return self.func("TIMESTAMP", shifted)
956
957        return date_add_interval_sql("DATE", kind)(self, expression)
def datesub_sql(self, expression: sqlglot.expressions.temporal.DateSub) -> str:
959    def datesub_sql(self, expression: exp.DateSub) -> str:
960        return self.dateadd_sql(expression)
def datediff_sql(self, expression: sqlglot.expressions.temporal.DateDiff) -> str:
962    def datediff_sql(self, expression: exp.DateDiff) -> str:
963        this = expression.this
964        expr = expression.expression
965        unit = expression.text("unit")
966        if not isinstance(expression.unit, exp.WeekStart) and unit not in DATE_DIFF_DATETIME_UNITS:
967            return self.func("DATE_DIFF", this, expr, unit_to_var(expression))
968
969        zoned_types = (exp.DType.TIMESTAMPTZ, exp.DType.TIMESTAMPLTZ)
970        zoned = this.unnest().is_type(*zoned_types) or expr.unnest().is_type(*zoned_types)
971        if zoned:
972            self.unsupported("DATE_DIFF reads TIMESTAMP WITH TIME ZONE values in UTC")
973
974        if unit == "WEEK" and not expression.args.get("date_part_boundary"):
975            self.unsupported("DATE_DIFF counts the Sundays crossed, not whole weeks")
976
977        if not zoned and not (_is_timestamp(this) or _is_timestamp(expr)):
978            return self.func("DATE_DIFF", this, expr, unit_to_var(expression))
979
980        # These units only take DATE or DATETIME operands, so both sides are cast to DATETIME,
981        # which reads a TIMESTAMP in UTC
982        return self.func(
983            "DATE_DIFF",
984            _datetime_operand(this, self.dialect),
985            _datetime_operand(expr, self.dialect),
986            unit_to_var(expression),
987        )
def datetrunc_sql(self, expression: sqlglot.expressions.temporal.DateTrunc) -> str:
989    def datetrunc_sql(self, expression: exp.DateTrunc) -> str:
990        self._warn_unsupported_arg(expression, "century_from_zero")
991        unit = expression.unit
992        if unit.is_string and unit.name.upper() in ("WEEK_OF_MONTH", "WEEK_OF_YEAR"):
993            self.unsupported(f"Unexpected interval unit: {unit.name}")
994        unit_sql = unit.name if unit.is_string else self.sql(unit)
995        return self.func("DATE_TRUNC", expression.this, unit_sql, expression.args.get("zone"))
def mod_sql(self, expression: sqlglot.expressions.core.Mod) -> str:
 997    def mod_sql(self, expression: exp.Mod) -> str:
 998        self.nullif_zero_divisor(expression)
 999        this = expression.this
1000        expr = expression.expression
1001        return self.func(
1002            "MOD",
1003            this.unnest() if isinstance(this, exp.Paren) else this,
1004            expr.unnest() if isinstance(expr, exp.Paren) else expr,
1005        )
def column_parts(self, expression: sqlglot.expressions.core.Column) -> str:
1007    def column_parts(self, expression: exp.Column) -> str:
1008        if expression.meta_get("quoted_column"):
1009            # If a column reference is of the form `dataset.table`.name, we need
1010            # to preserve the quoted table path, otherwise the reference breaks
1011            table_parts = ".".join(p.name for p in expression.parts[:-1])
1012            table_path = self.sql(exp.Identifier(this=table_parts, quoted=True))
1013            return f"{table_path}.{self.sql(expression, 'this')}"
1014
1015        return super().column_parts(expression)
def table_parts(self, expression: sqlglot.expressions.query.Table) -> str:
1017    def table_parts(self, expression: exp.Table) -> str:
1018        # Depending on the context, `x.y` may not resolve to the same data source as `x`.`y`, so
1019        # we need to make sure the correct quoting is used in each case.
1020        #
1021        # For example, if there is a CTE x that clashes with a schema name, then the former will
1022        # return the table y in that schema, whereas the latter will return the CTE's y column:
1023        #
1024        # - WITH x AS (SELECT [1, 2] AS y) SELECT * FROM x, `x.y`   -> cross join
1025        # - WITH x AS (SELECT [1, 2] AS y) SELECT * FROM x, `x`.`y` -> implicit unnest
1026        if expression.meta_get("quoted_table"):
1027            table_parts = ".".join(p.name for p in expression.parts)
1028            return self.sql(exp.Identifier(this=table_parts, quoted=True))
1029
1030        return super().table_parts(expression)
def timetostr_sql(self, expression: sqlglot.expressions.temporal.TimeToStr) -> str:
1032    def timetostr_sql(self, expression: exp.TimeToStr) -> str:
1033        this = expression.this
1034        if isinstance(this, exp.TsOrDsToDatetime):
1035            func_name = "FORMAT_DATETIME"
1036        elif isinstance(this, exp.TsOrDsToTimestamp):
1037            func_name = "FORMAT_TIMESTAMP"
1038        elif isinstance(this, exp.TsOrDsToTime):
1039            func_name = "FORMAT_TIME"
1040        else:
1041            func_name = "FORMAT_DATE"
1042
1043        time_expr = this if isinstance(this, self.TS_OR_DS_TYPES) else expression
1044        return self.func(
1045            func_name, self.format_time(expression), time_expr.this, expression.args.get("zone")
1046        )
def eq_sql(self, expression: sqlglot.expressions.core.EQ) -> str:
1048    def eq_sql(self, expression: exp.EQ) -> str:
1049        # Operands of = cannot be NULL in BigQuery
1050        if isinstance(expression.left, exp.Null) or isinstance(expression.right, exp.Null):
1051            if not isinstance(expression.parent, exp.Update):
1052                return "NULL"
1053
1054        _cast_zoneless_operand(expression)
1055        return self.binary(expression, "=")
def escape_sql(self, expression: sqlglot.expressions.core.Escape) -> str:
1057    def escape_sql(self, expression: exp.Escape) -> str:
1058        # BigQuery's LIKE has no ESCAPE clause and always escapes with a backslash, so a literal
1059        # pattern is rewritten to backslash escapes. UPPER/LOWER around it can't change a
1060        # caseless escape character, e.g. ^, so those patterns are rewritten too.
1061        like, char = expression.this.copy(), expression.expression.name
1062        pattern = like.expression
1063        if isinstance(pattern, (exp.Upper, exp.Lower)) and char.upper() == char.lower():
1064            pattern = pattern.this
1065        e = re.escape(char)
1066        if not (
1067            isinstance(like, exp.Like)
1068            and expression.expression.is_string
1069            and len(char) == 1
1070            and pattern.is_string
1071            and re.fullmatch(f"(?:[^{e}]|{e}[%_{e}])*", pattern.name)
1072        ):
1073            return super().escape_sql(expression)
1074
1075        # Escaped %, _ and backslash, and unescaped backslash, get a backslash
1076        pattern.set(
1077            "this",
1078            re.sub(
1079                f"{e}[%_{e}]|\\\\",
1080                lambda m: "\\" * (m[0][-1] in "%_\\") + m[0][-1],
1081                pattern.name,
1082            ),
1083        )
1084        return self.sql(like)
def attimezone_sql(self, expression: sqlglot.expressions.core.AtTimeZone) -> str:
1089    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
1090        parent = expression.parent
1091
1092        # BigQuery allows CAST(.. AS {STRING|TIMESTAMP} [FORMAT <fmt> [AT TIME ZONE <tz>]]).
1093        # Only the TIMESTAMP one should use the below conversion, when AT TIME ZONE is included.
1094        if not isinstance(parent, exp.Cast) or not parent.to.is_type("text"):
1095            this = expression.this
1096            if expression.args.get("session_zone"):
1097                # DATETIME(<ts>, <zone>) only accepts a TIMESTAMP and BigQuery reads a DATETIME
1098                # cast to TIMESTAMP as UTC, so this assumes the source session time zone is UTC
1099                this = exp.cast(this, exp.DType.TIMESTAMPTZ)
1100
1101            return self.func("TIMESTAMP", self.func("DATETIME", this, expression.args.get("zone")))
1102
1103        return super().attimezone_sql(expression)
def trycast_sql(self, expression: sqlglot.expressions.functions.TryCast) -> str:
1105    def trycast_sql(self, expression: exp.TryCast) -> str:
1106        return self.cast_sql(expression, safe_prefix="SAFE_")
def bracket_sql(self, expression: sqlglot.expressions.core.Bracket) -> str:
1108    def bracket_sql(self, expression: exp.Bracket) -> str:
1109        this = expression.this
1110        expressions = expression.expressions
1111
1112        if len(expressions) == 1 and this and this.is_type(exp.DType.STRUCT):
1113            arg = expressions[0]
1114            if arg.type is None:
1115                from sqlglot.optimizer.annotate_types import annotate_types
1116
1117                arg = annotate_types(arg, dialect=self.dialect)
1118
1119            if arg.type and arg.type.this in exp.DataType.TEXT_TYPES:
1120                # BQ doesn't support bracket syntax with string values for structs
1121                return f"{self.sql(this)}.{arg.name}"
1122
1123        expressions_sql = self.expressions(expression, flat=True)
1124        offset = expression.args.get("offset")
1125
1126        if offset == 0:
1127            expressions_sql = f"OFFSET({expressions_sql})"
1128        elif offset == 1:
1129            expressions_sql = f"ORDINAL({expressions_sql})"
1130        elif offset is not None:
1131            self.unsupported(f"Unsupported array offset: {offset}")
1132
1133        if expression.args.get("safe"):
1134            expressions_sql = f"SAFE_{expressions_sql}"
1135
1136        return f"{self.sql(this)}[{expressions_sql}]"
def in_unnest_op(self, expression: sqlglot.expressions.array.Unnest) -> str:
1138    def in_unnest_op(self, expression: exp.Unnest) -> str:
1139        return self.sql(expression)
def version_sql(self, expression: sqlglot.expressions.query.Version) -> str:
1141    def version_sql(self, expression: exp.Version) -> str:
1142        if expression.name == "TIMESTAMP":
1143            expression.set("this", "SYSTEM_TIME")
1144        return super().version_sql(expression)
def contains_sql(self, expression: sqlglot.expressions.string.Contains) -> str:
1146    def contains_sql(self, expression: exp.Contains) -> str:
1147        this = expression.this
1148        expr = expression.expression
1149
1150        if isinstance(this, exp.Lower) and isinstance(expr, exp.Lower):
1151            this = this.this
1152            expr = expr.this
1153
1154        return self.func("CONTAINS_SUBSTR", this, expr, expression.args.get("json_scope"))
def parsejson_sql(self, expression: sqlglot.expressions.json.ParseJSON) -> str:
1156    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
1157        if expression.args.get("is_literal"):
1158            return f"JSON {self.sql(expression, 'this')}"
1159        return super().parsejson_sql(expression)
def stgeogfromgeojson_sql(self, expression: sqlglot.expressions.array.StGeogFromGeoJson) -> str:
1161    def stgeogfromgeojson_sql(self, expression: exp.StGeogFromGeoJson) -> str:
1162        make_valid = expression.args.get("make_valid")
1163        if make_valid is not None and not isinstance(make_valid, exp.Kwarg):
1164            make_valid = exp.Kwarg(this=exp.var("make_valid"), expression=make_valid)
1165        return self.func(expression.sql_name(), expression.this, make_valid)
def cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
1167    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
1168        this = expression.this
1169
1170        # This ensures that inline type-annotated ARRAY literals like ARRAY<INT64>[1, 2, 3]
1171        # are roundtripped unaffected. The inner check excludes ARRAY(SELECT ...) expressions,
1172        # because they aren't literals and so the above syntax is invalid BigQuery.
1173        if isinstance(this, exp.Array):
1174            elem = seq_get(this.expressions, 0)
1175            if not (elem and elem.find(exp.Query)):
1176                return f"{self.sql(expression, 'to')}{self.sql(this)}"
1177
1178        return super().cast_sql(expression, safe_prefix=safe_prefix)
def ordered_sql(self, expression: sqlglot.expressions.core.Ordered) -> str:
1180    def ordered_sql(self, expression: exp.Ordered) -> str:
1181        order = expression.parent
1182        window = order.parent if isinstance(order, exp.Order) else None
1183        if not isinstance(window, exp.Window) or not _nondefault_null_order(expression):
1184            return super().ordered_sql(expression)
1185
1186        # A WINDOW definition can be used with different functions and frames.
1187        if isinstance(window.this, exp.Identifier):
1188            return super().ordered_sql(expression.copy())
1189
1190        spec = window.args.get("spec")
1191        if not _is_value_window(window) or (spec and spec.text("kind").upper() != "RANGE"):
1192            return super().ordered_sql(expression)
1193
1194        key = expression.this
1195        needs_null_key = key not in (window.args.get("partition_by") or [])
1196        if spec and any(isinstance(spec.args.get(bound), exp.Expr) for bound in ("start", "end")):
1197            # An offset RANGE allows only one key. With finite bounds, NULL keys can
1198            # only frame other NULLs, so their position relative to non-NULLs is immaterial.
1199            if needs_null_key and any(
1200                spec.text(bound).upper() == "UNBOUNDED" for bound in ("start", "end")
1201            ):
1202                return super().ordered_sql(expression)
1203            needs_null_key = False
1204
1205        desc = expression.args.get("desc")
1206        expression = expression.copy()
1207        expression.set("nulls_first", not desc)
1208        sql = super().ordered_sql(expression)
1209        if not needs_null_key:
1210            return sql
1211
1212        if isinstance(key, (exp.Not, exp.Predicate)):
1213            key = exp.paren(key)
1214        is_null = key.is_(exp.null())
1215        return f"{self.sql(is_null)}{' DESC' if desc else ''}, {sql}"
def clusterproperty_sql(self, expression: sqlglot.expressions.properties.ClusterProperty) -> str:
1217    def clusterproperty_sql(self, expression: exp.ClusterProperty) -> str:
1218        if expression.this:
1219            self.unsupported(f"Unsupported CLUSTER BY {self.sql(expression, 'this')}")
1220            return ""
1221        return self.op_expressions("CLUSTER BY", expression)
Inherited Members
sqlglot.generator.Generator
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
AUTO_REFRESH_BARE_INTERVALS
GROUPINGS_SEP
SUPPORTS_GROUPING_SETS_AS_SUFFIX
INDEX_ON
INOUT_SEPARATOR
DIRECTED_JOINS
SUPPORTS_NEAREST_JOIN
SUPPORTS_MATCH_CONDITION
MATCH_CONDITION_IN_ON
QUERY_HINT_SEP
IS_BOOL_ALLOWED
SAFE_INT_DIVISION
INT_DIV_OPERATOR
DUPLICATE_KEY_UPDATE_WITH_SET
LIMIT_IS_TOP
RETURNING_END
EXTRACT_ALLOWS_QUOTES
TZ_TO_WITH_TIME_ZONE
SELECT_KINDS
VALUES_AS_TABLE
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
ALTER_TABLE_ADD_COLUMNS_WRAPPED
SEMI_ANTI_JOIN_WITH_SIDE
COMPUTED_COLUMN_WITH_TYPE
SUPPORTS_TABLE_COPY
TABLESAMPLE_REQUIRES_PARENS
TABLESAMPLE_SIZE_IS_ROWS
TABLESAMPLE_KEYWORDS
TABLESAMPLE_WITH_METHOD
TABLESAMPLE_SEED_KEYWORD
HISTORICAL_DATA_POST_ALIAS
DATA_TYPE_SPECIFIERS_ALLOWED
ENSURE_BOOLS
CTE_RECURSIVE_KEYWORD_REQUIRED
SUPPORTS_SINGLE_ARG_CONCAT
LAST_DAY_SUPPORTS_DATE_PART
PIVOT_ALIAS_WITH_AS
INSERT_OVERWRITE
SUPPORTS_SELECT_INTO
SUPPORTS_OPTIMIZE
SUPPORTS_EXECUTE_IMMEDIATE
SUPPORTS_UNLOGGED_TABLES
SUPPORTS_CREATE_TABLE_LIKE
SUPPORTS_MODIFY_COLUMN
SUPPORTS_CHANGE_COLUMN
SUPPORTS_ALTER_COLUMN_NULLABILITY
SUPPORTS_ALTER_COLUMN_IF_EXISTS
LIKE_PROPERTY_INSIDE_SCHEMA
MULTI_ARG_DISTINCT
JSON_TYPE_REQUIRED_FOR_EXTRACTION
SUPPORTS_NESTED_JSON_SELECT
JSON_PATH_BRACKETED_KEY_SUPPORTED
JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
SUPPORTS_WINDOW_EXCLUDE
SET_OP_MODIFIERS
SET_OP_LIMITS
SET_OP_PARENTHESIZED_OPERANDS
COPY_PARAMS_ARE_WRAPPED
COPY_PARAMS_EQ_REQUIRED
COPY_HAS_INTO_KEYWORD
UNICODE_SUBSTITUTE
STAR_EXCEPT
BYTE_STRING_FUNCTION
QUOTE_JSON_PATH
PAD_FILL_PATTERN_IS_REQUIRED
ARRAY_CONCAT_IS_VAR_LEN
SUPPORTS_CONVERT_TIMEZONE
SUPPORTS_MEDIAN
ALTER_SET_WRAPPED
NORMALIZE_EXTRACT_DATE_PARTS
PARSE_JSON_NAME
ARRAY_SIZE_NAME
DAYOFWEEK_NAME
DAYOFWEEK_ZERO_BASED
VARIANCE_NAME
VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE
ALTER_SET_TYPE
ARRAY_SIZE_DIM_REQUIRED
SUPPORTS_BETWEEN_FLAGS
SUPPORTS_LIKE_QUANTIFIERS
MATCH_AGAINST_TABLE_PREFIX
SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD
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
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
WITH_SEPARATED_COMMENTS
EXCLUDE_COMMENTS
UNWRAPPED_INTERVAL_VALUES
PARAMETERIZABLE_TEXT_TYPES
EXPRESSIONS_WITHOUT_NESTED_CTES
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS
MOD_OPERATOR
BARE_OPERATORS
MOD_PAREN_PARENT_TYPES
ALTER_PARTITION_OPTIONS
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_sql
pseudocolumn_sql
columnposition_sql
columndef_sql
columnconstraint_sql
computedcolumnconstraint_sql
autoincrementcolumnconstraint_sql
compresscolumnconstraint_sql
generatedasidentitycolumnconstraint_sql
generatedasrowcolumnconstraint_sql
periodforsystemtimeconstraint_sql
notnullcolumnconstraint_sql
primarykeycolumnconstraint_sql
uniquecolumnconstraint_sql
inoutcolumnconstraint_sql
createable_sql
create_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
drop_sql
set_operation
set_operations
fetch_sql
limitoptions_sql
filter_sql
per_sql
hint_sql
indexparameters_sql
index_sql
dynamicidentifier_sql
identifier_sql
hex_sql
lowerhex_sql
inputoutputformat_sql
national_sql
partition_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
returning_sql
rowformatdelimitedproperty_sql
withtablehint_sql
indextablehint_sql
historicaldata_sql
table_sql
tableargument_sql
tablefromrows_sql
tablesample_sql
pivot_sql
tuple_sql
update_sql
values_sql
var_sql
into_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_op
lateral_sql
limit_sql
offset_sql
setitem_sql
set_sql
queryband_sql
pragma_sql
lock_sql
literal_sql
escape_str
loaddata_sql
null_sql
boolean_sql
booland_sql
boolor_sql
order_sql
withfill_sql
cluster_sql
distribute_sql
sort_sql
matchrecognizemeasure_sql
matchrecognize_sql
query_modifiers
options_modifier
forclause_sql
queryoption_sql
offset_limit_modifiers
after_limit_modifiers
select_sql
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
all_sql
any_sql
exists_sql
case_sql
constraint_sql
nextvaluefor_sql
dayofweek_sql
extract_date_part
extract_sql
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
interval_sql
return_sql
reference_sql
anonymous_sql
paren_sql
pos_sql
neg_sql
not_sql
alias_sql
pivotalias_sql
aliases_sql
atindex_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
strtotime_sql
strtodate_sql
parsedatetime_sql
currentdate_sql
collate_sql
command_sql
optimize_sql
comment_sql
mergetreettlaction_sql
mergetreettl_sql
transaction_sql
commit_sql
rollback_sql
altercolumn_sql
modifycolumn_sql
alterindex_sql
alterdiststyle_sql
altersortkey_sql
alterrename_sql
renamecolumn_sql
alterset_sql
alter_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
dpipe_sql
nullif_zero_divisor
div_sql
safedivide_sql
overlaps_sql
distance_sql
distancend_sql
dot_sql
nestedjsonselect_sql
propertyeq_sql
glob_sql
gt_sql
gte_sql
is_sql
like_sql
ilike_sql
match_sql
similarto_sql
lt_sql
lte_sql
mul_sql
neq_sql
nullsafeeq_sql
nullsafeneq_sql
sub_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
arrayinsert_sql
arrayany_sql
struct_sql
partitionrange_sql
truncatetable_sql
convert_sql
copyparameter_sql
credentials_sql
copy_sql
semicolon_sql
datadeletionproperty_sql
maskingpolicycolumnconstraint_sql
gapfill_sql
scope_resolution
scoperesolution_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
chr_sql
weightstring_sql
block_sql
functionspecification_sql
storedprocedure_sql
ifblock_sql
casestatement_sql
whileblock_sql
loopblock_sql
repeatblock_sql
leave_sql
iterate_sql
execute_sql
executesql_sql
executeimmediate_sql
altermodifysqlsecurity_sql
usingproperty_sql
renameindex_sql