Edit on GitHub

sqlglot.generator

   1from __future__ import annotations
   2
   3import logging
   4import re
   5import typing as t
   6from collections import defaultdict
   7from decimal import Decimal
   8from functools import reduce, wraps
   9
  10from sqlglot import exp
  11from sqlglot.errors import ErrorLevel, UnsupportedError, concat_messages
  12from sqlglot.expressions import apply_index_offset
  13from sqlglot.expressions.core import maybe_parse
  14from sqlglot.helper import csv, name_sequence, seq_get
  15from sqlglot.jsonpath import ALL_JSON_PATH_PARTS, JSON_PATH_PART_TRANSFORMS
  16from sqlglot.time import format_time
  17from sqlglot.tokens import TokenType
  18
  19if t.TYPE_CHECKING:
  20    from sqlglot._typing import E
  21    from sqlglot.dialects.dialect import DialectType
  22
  23    G = t.TypeVar("G", bound="Generator")
  24    GeneratorMethod = t.Callable[[G, E], str]
  25
  26logger = logging.getLogger("sqlglot")
  27
  28_HIGH_BYTE_RE = re.compile(r"[\x80-\xff]")
  29
  30ESCAPED_UNICODE_RE = re.compile(r"\\(\d+)")
  31UNSUPPORTED_TEMPLATE = "Argument '{}' is not supported for expression '{}' when targeting {}."
  32
  33
  34def unsupported_args(
  35    *args: str | tuple[str, str],
  36) -> t.Callable[[GeneratorMethod], GeneratorMethod]:
  37    """
  38    Decorator that can be used to mark certain args of an `Expr` subclass as unsupported.
  39    It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).
  40    """
  41    diagnostic_by_arg: dict[str, str | None] = {}
  42    for arg in args:
  43        if isinstance(arg, str):
  44            diagnostic_by_arg[arg] = None
  45        else:
  46            diagnostic_by_arg[arg[0]] = arg[1]
  47
  48    def decorator(func: GeneratorMethod) -> GeneratorMethod:
  49        @wraps(func)
  50        def _func(generator: G, expression: E) -> str:
  51            for arg_name, diagnostic in diagnostic_by_arg.items():
  52                generator._warn_unsupported_arg(expression, arg_name, diagnostic)
  53
  54            return func(generator, expression)
  55
  56        return _func
  57
  58    return decorator
  59
  60
  61AFTER_HAVING_MODIFIER_TRANSFORMS: dict[str, t.Any] = {
  62    "windows": lambda self, e: (
  63        self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True)
  64        if e.args.get("windows")
  65        else ""
  66    ),
  67    "qualify": lambda self, e: self.sql(e, "qualify"),
  68}
  69
  70
  71_DISPATCH_CACHE: dict[type[Generator], dict[type[exp.Expr], t.Callable[..., str]]] = {}
  72
  73
  74def _build_dispatch(
  75    cls: type[Generator],
  76) -> dict[type[exp.Expr], t.Callable[..., str]]:
  77    dispatch: dict[type[exp.Expr], t.Callable[..., str]] = dict(cls.TRANSFORMS)
  78
  79    for attr_name in dir(cls):
  80        if not attr_name.endswith("_sql") or attr_name.startswith("_"):
  81            continue
  82
  83        expr_key = attr_name[:-4]
  84        expr_cls = exp.EXPR_CLASSES.get(expr_key)
  85
  86        if expr_cls and expr_cls not in dispatch:
  87            dispatch[expr_cls] = getattr(cls, attr_name)
  88
  89    return dispatch
  90
  91
  92class Generator:
  93    """
  94    Generator converts a given syntax tree to the corresponding SQL string.
  95
  96    Args:
  97        pretty: Whether to format the produced SQL string.
  98            Default: False.
  99        identify: Determines when an identifier should be quoted. Possible values are:
 100            False (default): Never quote, except in cases where it's mandatory by the dialect.
 101            True: Always quote except for specials cases.
 102            'safe': Only quote identifiers that are case insensitive.
 103        normalize: Whether to normalize identifiers to lowercase.
 104            Default: False.
 105        pad: The pad size in a formatted string. For example, this affects the indentation of
 106            a projection in a query, relative to its nesting level.
 107            Default: 2.
 108        indent: The indentation size in a formatted string. For example, this affects the
 109            indentation of subqueries and filters under a `WHERE` clause.
 110            Default: 2.
 111        normalize_functions: How to normalize function names. Possible values are:
 112            "upper" or True (default): Convert names to uppercase.
 113            "lower": Convert names to lowercase.
 114            False: Disables function name normalization.
 115        unsupported_level: Determines the generator's behavior when it encounters unsupported expressions.
 116            Default ErrorLevel.WARN.
 117        max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError.
 118            This is only relevant if unsupported_level is ErrorLevel.RAISE.
 119            Default: 3
 120        leading_comma: Whether the comma is leading or trailing in select expressions.
 121            This is only relevant when generating in pretty mode.
 122            Default: False
 123        max_text_width: The max number of characters in a segment before creating new lines in pretty mode.
 124            The default is on the smaller end because the length only represents a segment and not the true
 125            line length.
 126            Default: 80
 127        comments: Whether to preserve comments in the output SQL code.
 128            Default: True
 129    """
 130
 131    TRANSFORMS: t.ClassVar[dict[type[exp.Expr], t.Callable[..., str]]] = {
 132        **JSON_PATH_PART_TRANSFORMS,
 133        exp.Adjacent: lambda self, e: self.binary(e, "-|-"),
 134        exp.AllowedValuesProperty: lambda self, e: (
 135            f"ALLOWED_VALUES {self.expressions(e, flat=True)}"
 136        ),
 137        exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"),
 138        exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "),
 139        exp.ArrayContainedBy: lambda self, e: self.binary(e, "<@"),
 140        exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"),
 141        exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"),
 142        exp.AssumeColumnConstraint: lambda self, e: f"ASSUME ({self.sql(e, 'this')})",
 143        exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}",
 144        exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}",
 145        exp.BinaryColumnConstraint: lambda *_: "BINARY",
 146        exp.CaseSpecificColumnConstraint: lambda _, e: (
 147            f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC"
 148        ),
 149        exp.CalledOnNullInputProperty: lambda *_: "CALLED ON NULL INPUT",