Edit on GitHub

# sqlglot.dialects.duckdb

View Source

      1from __future__ import annotations
      2
      3import typing as t
      4
      5from sqlglot import exp, generator, parser, tokens
      6from sqlglot.dialects.dialect import (
      7    Dialect,
      8    approx_count_distinct_sql,
      9    arrow_json_extract_scalar_sql,
     10    arrow_json_extract_sql,
     11    datestrtodate_sql,
     12    format_time_lambda,
     13    no_comment_column_constraint_sql,
     14    no_properties_sql,
     15    no_safe_divide_sql,
     16    pivot_column_names,
     17    rename_func,
     18    str_position_sql,
     19    str_to_time_sql,
     20    timestamptrunc_sql,
     21    timestrtotime_sql,
     22    ts_or_ds_to_date_sql,
     23)
     24from sqlglot.helper import seq_get
     25from sqlglot.tokens import TokenType
     26
     27
     28def _ts_or_ds_add_sql(self: generator.Generator, expression: exp.TsOrDsAdd) -> str:
     29    this = self.sql(expression, "this")
     30    unit = self.sql(expression, "unit").strip("'") or "DAY"
     31    return f"CAST({this} AS DATE) + {self.sql(exp.Interval(this=expression.expression, unit=unit))}"
     32
     33
     34def _date_add_sql(self: generator.Generator, expression: exp.DateAdd) -> str:
     35    this = self.sql(expression, "this")
     36    unit = self.sql(expression, "unit").strip("'") or "DAY"
     37    return f"{this} + {self.sql(exp.Interval(this=expression.expression, unit=unit))}"
     38
     39
     40def _array_sort_sql(self: generator.Generator, expression: exp.ArraySort) -> str:
     41    if expression.expression:
     42        self.unsupported("DUCKDB ARRAY_SORT does not support a comparator")
     43    return f"ARRAY_SORT({self.sql(expression, 'this')})"
     44
     45
     46def _sort_array_sql(self: generator.Generator, expression: exp.SortArray) -> str:
     47    this = self.sql(expression, "this")
     48    if expression.args.get("asc") == exp.false():
     49        return f"ARRAY_REVERSE_SORT({this})"
     50    return f"ARRAY_SORT({this})"
     51
     52
     53def _sort_array_reverse(args: t.List) -> exp.Expression:
     54    return exp.SortArray(this=seq_get(args, 0), asc=exp.false())
     55
     56
     57def _parse_date_diff(args: t.List) -> exp.Expression:
     58    return exp.DateDiff(
     59        this=seq_get(args, 2),
     60        expression=seq_get(args, 1),
     61        unit=seq_get(args, 0),
     62    )
     63
     64
     65def _struct_sql(self: generator.Generator, expression: exp.Struct) -> str:
     66    args = [
     67        f"'{e.name or e.this.name}': {self.sql(e, 'expression')}" for e in expression.expressions
     68    ]
     69    return f"{{{', '.join(args)}}}"
     70
     71
     72def _datatype_sql(self: generator.Generator, expression: exp.DataType) -> str:
     73    if expression.this == exp.DataType.Type.ARRAY:
     74        return f"{self.expressions(expression, flat=True)}[]"
     75    return self.datatype_sql(expression)
     76
     77
     78def _regexp_extract_sql(self: generator.Generator, expression: exp.RegexpExtract) -> str:
     79    bad_args = list(filter(expression.args.get, ("position", "occurrence")))
     80    if bad_args:
     81        self.unsupported(f"REGEXP_EXTRACT does not support arg(s) {bad_args}")
     82
     83    return self.func(
     84        "REGEXP_EXTRACT",
     85        expression.args.get("this"),
     86        expression.args.get("expression"),
     87        expression.args.get("group"),
     88    )
     89
     90
     91class DuckDB(Dialect):
     92    null_ordering = "nulls_are_last"
     93
     94    class Tokenizer(tokens.Tokenizer):
     95        KEYWORDS = {
     96            **tokens.Tokenizer.KEYWORDS,
     97            "~": TokenType.RLIKE,
     98            ":=": TokenType.EQ,
     99            "//": TokenType.DIV,
    100            "ATTACH": TokenType.COMMAND,
    101            "BINARY": TokenType.VARBINARY,
    102            "BPCHAR": TokenType.TEXT,
    103            "BITSTRING": TokenType.BIT,
    104            "CHAR": TokenType.TEXT,
    105            "CHARACTER VARYING": TokenType.TEXT,
    106            "EXCLUDE": TokenType.EXCEPT,
    107            "INT1": TokenType.TINYINT,
    108            "LOGICAL": TokenType.BOOLEAN,
    109            "NUMERIC": TokenType.DOUBLE,
    110            "SIGNED": TokenType.INT,
    111            "STRING": TokenType.VARCHAR,
    112            "UBIGINT": TokenType.UBIGINT,
    113            "UINTEGER": TokenType.UINT,
    114            "USMALLINT": TokenType.USMALLINT,
    115            "UTINYINT": TokenType.UTINYINT,
    116        }
    117
    118    class Parser(parser.Parser):
    119        FUNCTIONS = {
    120            **parser.Parser.FUNCTIONS,
    121            "ARRAY_LENGTH": exp.ArraySize.from_arg_list,
    122            "ARRAY_SORT": exp.SortArray.from_arg_list,
    123            "ARRAY_REVERSE_SORT": _sort_array_reverse,
    124            "DATEDIFF": _parse_date_diff,
    125            "DATE_DIFF": _parse_date_diff,
    126            "EPOCH": exp.TimeToUnix.from_arg_list,
    127            "EPOCH_MS": lambda args: exp.UnixToTime(
    128                this=exp.Div(
    129                    this=seq_get(args, 0),
    130                    expression=exp.Literal.number(1000),
    131                )
    132            ),
    133            "LIST_REVERSE_SORT": _sort_array_reverse,
    134            "LIST_SORT": exp.SortArray.from_arg_list,
    135            "LIST_VALUE": exp.Array.from_arg_list,
    136            "REGEXP_MATCHES": exp.RegexpLike.from_arg_list,
    137            "STRFTIME": format_time_lambda(exp.TimeToStr, "duckdb"),
    138            "STRING_SPLIT": exp.Split.from_arg_list,
    139            "STRING_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
    140            "STRING_TO_ARRAY": exp.Split.from_arg_list,
    141            "STRPTIME": format_time_lambda(exp.StrToTime, "duckdb"),
    142            "STRUCT_PACK": exp.Struct.from_arg_list,
    143            "STR_SPLIT": exp.Split.from_arg_list,
    144            "STR_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
    145            "TO_TIMESTAMP": exp.UnixToTime.from_arg_list,
    146            "UNNEST": exp.Explode.from_arg_list,
    147        }
    148
    149        TYPE_TOKENS = {
    150            *parser.Parser.TYPE_TOKENS,
    151            TokenType.UBIGINT,
    152            TokenType.UINT,
    153            TokenType.USMALLINT,
    154            TokenType.UTINYINT,
    155        }
    156
    157        def _pivot_column_names(self, aggregations: t.List[exp.Expression]) -> t.List[str]:
    158            if len(aggregations) == 1:
    159                return super()._pivot_column_names(aggregations)
    160            return pivot_column_names(aggregations, dialect="duckdb")
    161
    162    class Generator(generator.Generator):
    163        JOIN_HINTS = False
    164        TABLE_HINTS = False
    165        LIMIT_FETCH = "LIMIT"
    166        STRUCT_DELIMITER = ("(", ")")
    167        RENAME_TABLE_WITH_DB = False
    168
    169        TRANSFORMS = {
    170            **generator.Generator.TRANSFORMS,
    171            exp.ApproxDistinct: approx_count_distinct_sql,
    172            exp.Array: lambda self, e: self.func("ARRAY", e.expressions[0])
    173            if isinstance(seq_get(e.expressions, 0), exp.Select)
    174            else rename_func("LIST_VALUE")(self, e),
    175            exp.ArraySize: rename_func("ARRAY_LENGTH"),
    176            exp.ArraySort: _array_sort_sql,
    177            exp.ArraySum: rename_func("LIST_SUM"),
    178            exp.CommentColumnConstraint: no_comment_column_constraint_sql,
    179            exp.CurrentDate: lambda self, e: "CURRENT_DATE",
    180            exp.CurrentTime: lambda self, e: "CURRENT_TIME",
    181            exp.CurrentTimestamp: lambda self, e: "CURRENT_TIMESTAMP",
    182            exp.DayOfMonth: rename_func("DAYOFMONTH"),
    183            exp.DayOfWeek: rename_func("DAYOFWEEK"),
    184            exp.DayOfYear: rename_func("DAYOFYEAR"),
    185            exp.DataType: _datatype_sql,
    186            exp.DateAdd: _date_add_sql,
    187            exp.DateDiff: lambda self, e: self.func(
    188                "DATE_DIFF", f"'{e.args.get('unit', 'day')}'", e.expression, e.this
    189            ),
    190            exp.DateStrToDate: datestrtodate_sql,
    191            exp.DateToDi: lambda self, e: f"CAST(STRFTIME({self.sql(e, 'this')}, {DuckDB.dateint_format}) AS INT)",
    192            exp.DiToDate: lambda self, e: f"CAST(STRPTIME(CAST({self.sql(e, 'this')} AS TEXT), {DuckDB.dateint_format}) AS DATE)",
    193            exp.Explode: rename_func("UNNEST"),
    194            exp.IntDiv: lambda self, e: self.binary(e, "//"),
    195            exp.JSONExtract: arrow_json_extract_sql,
    196            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    197            exp.JSONBExtract: arrow_json_extract_sql,
    198            exp.JSONBExtractScalar: arrow_json_extract_scalar_sql,
    199            exp.LogicalOr: rename_func("BOOL_OR"),
    200            exp.LogicalAnd: rename_func("BOOL_AND"),
    201            exp.Properties: no_properties_sql,
    202            exp.RegexpExtract: _regexp_extract_sql,
    203            exp.RegexpLike: rename_func("REGEXP_MATCHES"),
    204            exp.RegexpSplit: rename_func("STR_SPLIT_REGEX"),
    205            exp.SafeDivide: no_safe_divide_sql,
    206            exp.Split: rename_func("STR_SPLIT"),
    207            exp.SortArray: _sort_array_sql,
    208            exp.StrPosition: str_position_sql,
    209            exp.StrToDate: lambda self, e: f"CAST({str_to_time_sql(self, e)} AS DATE)",
    210            exp.StrToTime: str_to_time_sql,
    211            exp.StrToUnix: lambda self, e: f"EPOCH(STRPTIME({self.sql(e, 'this')}, {self.format_time(e)}))",
    212            exp.Struct: _struct_sql,
    213            exp.TimestampTrunc: timestamptrunc_sql,
    214            exp.TimeStrToDate: lambda self, e: f"CAST({self.sql(e, 'this')} AS DATE)",
    215            exp.TimeStrToTime: timestrtotime_sql,
    216            exp.TimeStrToUnix: lambda self, e: f"EPOCH(CAST({self.sql(e, 'this')} AS TIMESTAMP))",
    217            exp.TimeToStr: lambda self, e: f"STRFTIME({self.sql(e, 'this')}, {self.format_time(e)})",
    218            exp.TimeToUnix: rename_func("EPOCH"),
    219            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS TEXT), '-', ''), 1, 8) AS INT)",
    220            exp.TsOrDsAdd: _ts_or_ds_add_sql,
    221            exp.TsOrDsToDate: ts_or_ds_to_date_sql("duckdb"),
    222            exp.UnixToStr: lambda self, e: f"STRFTIME(TO_TIMESTAMP({self.sql(e, 'this')}), {self.format_time(e)})",
    223            exp.UnixToTime: rename_func("TO_TIMESTAMP"),
    224            exp.UnixToTimeStr: lambda self, e: f"CAST(TO_TIMESTAMP({self.sql(e, 'this')}) AS TEXT)",
    225            exp.WeekOfYear: rename_func("WEEKOFYEAR"),
    226        }
    227
    228        TYPE_MAPPING = {
    229            **generator.Generator.TYPE_MAPPING,
    230            exp.DataType.Type.BINARY: "BLOB",
    231            exp.DataType.Type.CHAR: "TEXT",
    232            exp.DataType.Type.FLOAT: "REAL",
    233            exp.DataType.Type.NCHAR: "TEXT",
    234            exp.DataType.Type.NVARCHAR: "TEXT",
    235            exp.DataType.Type.UINT: "UINTEGER",
    236            exp.DataType.Type.VARBINARY: "BLOB",
    237            exp.DataType.Type.VARCHAR: "TEXT",
    238        }
    239
    240        STAR_MAPPING = {**generator.Generator.STAR_MAPPING, "except": "EXCLUDE"}
    241
    242        PROPERTIES_LOCATION = {
    243            **generator.Generator.PROPERTIES_LOCATION,
    244            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    245        }
    246
    247        def tablesample_sql(
    248            self, expression: exp.TableSample, seed_prefix: str = "SEED", sep: str = " AS "
    249        ) -> str:
    250            return super().tablesample_sql(expression, seed_prefix="REPEATABLE", sep=sep)

class DuckDB(sqlglot.dialects.dialect.Dialect): View Source

     92class DuckDB(Dialect):
     93    null_ordering = "nulls_are_last"
     94
     95    class Tokenizer(tokens.Tokenizer):
     96        KEYWORDS = {
     97            **tokens.Tokenizer.KEYWORDS,
     98            "~": TokenType.RLIKE,
     99            ":=": TokenType.EQ,
    100            "//": TokenType.DIV,
    101            "ATTACH": TokenType.COMMAND,
    102            "BINARY": TokenType.VARBINARY,
    103            "BPCHAR": TokenType.TEXT,
    104            "BITSTRING": TokenType.BIT,
    105            "CHAR": TokenType.TEXT,
    106            "CHARACTER VARYING": TokenType.TEXT,
    107            "EXCLUDE": TokenType.EXCEPT,
    108            "INT1": TokenType.TINYINT,
    109            "LOGICAL": TokenType.BOOLEAN,
    110            "NUMERIC": TokenType.DOUBLE,
    111            "SIGNED": TokenType.INT,
    112            "STRING": TokenType.VARCHAR,
    113            "UBIGINT": TokenType.UBIGINT,
    114            "UINTEGER": TokenType.UINT,
    115            "USMALLINT": TokenType.USMALLINT,
    116            "UTINYINT": TokenType.UTINYINT,
    117        }
    118
    119    class Parser(parser.Parser):
    120        FUNCTIONS = {
    121            **parser.Parser.FUNCTIONS,
    122            "ARRAY_LENGTH": exp.ArraySize.from_arg_list,
    123            "ARRAY_SORT": exp.SortArray.from_arg_list,
    124            "ARRAY_REVERSE_SORT": _sort_array_reverse,
    125            "DATEDIFF": _parse_date_diff,
    126            "DATE_DIFF": _parse_date_diff,
    127            "EPOCH": exp.TimeToUnix.from_arg_list,
    128            "EPOCH_MS": lambda args: exp.UnixToTime(
    129                this=exp.Div(
    130                    this=seq_get(args, 0),
    131                    expression=exp.Literal.number(1000),
    132                )
    133            ),
    134            "LIST_REVERSE_SORT": _sort_array_reverse,
    135            "LIST_SORT": exp.SortArray.from_arg_list,
    136            "LIST_VALUE": exp.Array.from_arg_list,
    137            "REGEXP_MATCHES": exp.RegexpLike.from_arg_list,
    138            "STRFTIME": format_time_lambda(exp.TimeToStr, "duckdb"),
    139            "STRING_SPLIT": exp.Split.from_arg_list,
    140            "STRING_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
    141            "STRING_TO_ARRAY": exp.Split.from_arg_list,
    142            "STRPTIME": format_time_lambda(exp.StrToTime, "duckdb"),
    143            "STRUCT_PACK": exp.Struct.from_arg_list,
    144            "STR_SPLIT": exp.Split.from_arg_list,
    145            "STR_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
    146            "TO_TIMESTAMP": exp.UnixToTime.from_arg_list,
    147            "UNNEST": exp.Explode.from_arg_list,
    148        }
    149
    150        TYPE_TOKENS = {
    151            *parser.Parser.TYPE_TOKENS,
    152            TokenType.UBIGINT,
    153            TokenType.UINT,
    154            TokenType.USMALLINT,
    155            TokenType.UTINYINT,
    156        }
    157
    158        def _pivot_column_names(self, aggregations: t.List[exp.Expression]) -> t.List[str]:
    159            if len(aggregations) == 1:
    160                return super()._pivot_column_names(aggregations)
    161            return pivot_column_names(aggregations, dialect="duckdb")
    162
    163    class Generator(generator.Generator):
    164        JOIN_HINTS = False
    165        TABLE_HINTS = False
    166        LIMIT_FETCH = "LIMIT"
    167        STRUCT_DELIMITER = ("(", ")")
    168        RENAME_TABLE_WITH_DB = False
    169
    170        TRANSFORMS = {
    171            **generator.Generator.TRANSFORMS,
    172            exp.ApproxDistinct: approx_count_distinct_sql,
    173            exp.Array: lambda self, e: self.func("ARRAY", e.expressions[0])
    174            if isinstance(seq_get(e.expressions, 0), exp.Select)
    175            else rename_func("LIST_VALUE")(self, e),
    176            exp.ArraySize: rename_func("ARRAY_LENGTH"),
    177            exp.ArraySort: _array_sort_sql,
    178            exp.ArraySum: rename_func("LIST_SUM"),
    179            exp.CommentColumnConstraint: no_comment_column_constraint_sql,
    180            exp.CurrentDate: lambda self, e: "CURRENT_DATE",
    181            exp.CurrentTime: lambda self, e: "CURRENT_TIME",
    182            exp.CurrentTimestamp: lambda self, e: "CURRENT_TIMESTAMP",
    183            exp.DayOfMonth: rename_func("DAYOFMONTH"),
    184            exp.DayOfWeek: rename_func("DAYOFWEEK"),
    185            exp.DayOfYear: rename_func("DAYOFYEAR"),
    186            exp.DataType: _datatype_sql,
    187            exp.DateAdd: _date_add_sql,
    188            exp.DateDiff: lambda self, e: self.func(
    189                "DATE_DIFF", f"'{e.args.get('unit', 'day')}'", e.expression, e.this
    190            ),
    191            exp.DateStrToDate: datestrtodate_sql,
    192            exp.DateToDi: lambda self, e: f"CAST(STRFTIME({self.sql(e, 'this')}, {DuckDB.dateint_format}) AS INT)",
    193            exp.DiToDate: lambda self, e: f"CAST(STRPTIME(CAST({self.sql(e, 'this')} AS TEXT), {DuckDB.dateint_format}) AS DATE)",
    194            exp.Explode: rename_func("UNNEST"),
    195            exp.IntDiv: lambda self, e: self.binary(e, "//"),
    196            exp.JSONExtract: arrow_json_extract_sql,
    197            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    198            exp.JSONBExtract: arrow_json_extract_sql,
    199            exp.JSONBExtractScalar: arrow_json_extract_scalar_sql,
    200            exp.LogicalOr: rename_func("BOOL_OR"),
    201            exp.LogicalAnd: rename_func("BOOL_AND"),
    202            exp.Properties: no_properties_sql,
    203            exp.RegexpExtract: _regexp_extract_sql,
    204            exp.RegexpLike: rename_func("REGEXP_MATCHES"),
    205            exp.RegexpSplit: rename_func("STR_SPLIT_REGEX"),
    206            exp.SafeDivide: no_safe_divide_sql,
    207            exp.Split: rename_func("STR_SPLIT"),
    208            exp.SortArray: _sort_array_sql,
    209            exp.StrPosition: str_position_sql,
    210            exp.StrToDate: lambda self, e: f"CAST({str_to_time_sql(self, e)} AS DATE)",
    211            exp.StrToTime: str_to_time_sql,
    212            exp.StrToUnix: lambda self, e: f"EPOCH(STRPTIME({self.sql(e, 'this')}, {self.format_time(e)}))",
    213            exp.Struct: _struct_sql,
    214            exp.TimestampTrunc: timestamptrunc_sql,
    215            exp.TimeStrToDate: lambda self, e: f"CAST({self.sql(e, 'this')} AS DATE)",
    216            exp.TimeStrToTime: timestrtotime_sql,
    217            exp.TimeStrToUnix: lambda self, e: f"EPOCH(CAST({self.sql(e, 'this')} AS TIMESTAMP))",
    218            exp.TimeToStr: lambda self, e: f"STRFTIME({self.sql(e, 'this')}, {self.format_time(e)})",
    219            exp.TimeToUnix: rename_func("EPOCH"),
    220            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS TEXT), '-', ''), 1, 8) AS INT)",
    221            exp.TsOrDsAdd: _ts_or_ds_add_sql,
    222            exp.TsOrDsToDate: ts_or_ds_to_date_sql("duckdb"),
    223            exp.UnixToStr: lambda self, e: f"STRFTIME(TO_TIMESTAMP({self.sql(e, 'this')}), {self.format_time(e)})",
    224            exp.UnixToTime: rename_func("TO_TIMESTAMP"),
    225            exp.UnixToTimeStr: lambda self, e: f"CAST(TO_TIMESTAMP({self.sql(e, 'this')}) AS TEXT)",
    226            exp.WeekOfYear: rename_func("WEEKOFYEAR"),
    227        }
    228
    229        TYPE_MAPPING = {
    230            **generator.Generator.TYPE_MAPPING,
    231            exp.DataType.Type.BINARY: "BLOB",
    232            exp.DataType.Type.CHAR: "TEXT",
    233            exp.DataType.Type.FLOAT: "REAL",
    234            exp.DataType.Type.NCHAR: "TEXT",
    235            exp.DataType.Type.NVARCHAR: "TEXT",
    236            exp.DataType.Type.UINT: "UINTEGER",
    237            exp.DataType.Type.VARBINARY: "BLOB",
    238            exp.DataType.Type.VARCHAR: "TEXT",
    239        }
    240
    241        STAR_MAPPING = {**generator.Generator.STAR_MAPPING, "except": "EXCLUDE"}
    242
    243        PROPERTIES_LOCATION = {
    244            **generator.Generator.PROPERTIES_LOCATION,
    245            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    246        }
    247
    248        def tablesample_sql(
    249            self, expression: exp.TableSample, seed_prefix: str = "SEED", sep: str = " AS "
    250        ) -> str:
    251            return super().tablesample_sql(expression, seed_prefix="REPEATABLE", sep=sep)

##### Inherited Members

sqlglot.dialects.dialect.Dialect
  get_or_raise
  format_time
  parse
  parse_into
  generate
  transpile
  tokenize
  parser
  generator

class DuckDB.Tokenizer(sqlglot.tokens.Tokenizer): View Source

     95    class Tokenizer(tokens.Tokenizer):
     96        KEYWORDS = {
     97            **tokens.Tokenizer.KEYWORDS,
     98            "~": TokenType.RLIKE,
     99            ":=": TokenType.EQ,
    100            "//": TokenType.DIV,
    101            "ATTACH": TokenType.COMMAND,
    102            "BINARY": TokenType.VARBINARY,
    103            "BPCHAR": TokenType.TEXT,
    104            "BITSTRING": TokenType.BIT,
    105            "CHAR": TokenType.TEXT,
    106            "CHARACTER VARYING": TokenType.TEXT,
    107            "EXCLUDE": TokenType.EXCEPT,
    108            "INT1": TokenType.TINYINT,
    109            "LOGICAL": TokenType.BOOLEAN,
    110            "NUMERIC": TokenType.DOUBLE,
    111            "SIGNED": TokenType.INT,
    112            "STRING": TokenType.VARCHAR,
    113            "UBIGINT": TokenType.UBIGINT,
    114            "UINTEGER": TokenType.UINT,
    115            "USMALLINT": TokenType.USMALLINT,
    116            "UTINYINT": TokenType.UTINYINT,
    117        }

##### Inherited Members

sqlglot.tokens.Tokenizer
  reset
  tokenize

class DuckDB.Parser(sqlglot.parser.Parser): View Source

    119    class Parser(parser.Parser):
    120        FUNCTIONS = {
    121            **parser.Parser.FUNCTIONS,
    122            "ARRAY_LENGTH": exp.ArraySize.from_arg_list,
    123            "ARRAY_SORT": exp.SortArray.from_arg_list,
    124            "ARRAY_REVERSE_SORT": _sort_array_reverse,
    125            "DATEDIFF": _parse_date_diff,
    126            "DATE_DIFF": _parse_date_diff,
    127            "EPOCH": exp.TimeToUnix.from_arg_list,
    128            "EPOCH_MS": lambda args: exp.UnixToTime(
    129                this=exp.Div(
    130                    this=seq_get(args, 0),
    131                    expression=exp.Literal.number(1000),
    132                )
    133            ),
    134            "LIST_REVERSE_SORT": _sort_array_reverse,
    135            "LIST_SORT": exp.SortArray.from_arg_list,
    136            "LIST_VALUE": exp.Array.from_arg_list,
    137            "REGEXP_MATCHES": exp.RegexpLike.from_arg_list,
    138            "STRFTIME": format_time_lambda(exp.TimeToStr, "duckdb"),
    139            "STRING_SPLIT": exp.Split.from_arg_list,
    140            "STRING_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
    141            "STRING_TO_ARRAY": exp.Split.from_arg_list,
    142            "STRPTIME": format_time_lambda(exp.StrToTime, "duckdb"),
    143            "STRUCT_PACK": exp.Struct.from_arg_list,
    144            "STR_SPLIT": exp.Split.from_arg_list,
    145            "STR_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
    146            "TO_TIMESTAMP": exp.UnixToTime.from_arg_list,
    147            "UNNEST": exp.Explode.from_arg_list,
    148        }
    149
    150        TYPE_TOKENS = {
    151            *parser.Parser.TYPE_TOKENS,
    152            TokenType.UBIGINT,
    153            TokenType.UINT,
    154            TokenType.USMALLINT,
    155            TokenType.UTINYINT,
    156        }
    157
    158        def _pivot_column_names(self, aggregations: t.List[exp.Expression]) -> t.List[str]:
    159            if len(aggregations) == 1:
    160                return super()._pivot_column_names(aggregations)
    161            return pivot_column_names(aggregations, dialect="duckdb")

Parser consumes a list of tokens produced by the `sqlglot.tokens.Tokenizer` and produces a parsed syntax tree.

###### Arguments:

- error_level: the desired error level. Default: ErrorLevel.RAISE
- error_message_context: determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 50.
- index_offset: Index offset for arrays eg ARRAY[0] vs ARRAY[1] as the head of a list. Default: 0
- alias_post_tablesample: If the table alias comes after tablesample. Default: False
- max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3
- null_ordering: Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"

##### Inherited Members

sqlglot.parser.Parser
  Parser
  reset
  parse
  parse_into
  check_errors
  raise_error
  expression
  validate_expression

class DuckDB.Generator(sqlglot.generator.Generator): View Source

    163    class Generator(generator.Generator):
    164        JOIN_HINTS = False
    165        TABLE_HINTS = False
    166        LIMIT_FETCH = "LIMIT"
    167        STRUCT_DELIMITER = ("(", ")")
    168        RENAME_TABLE_WITH_DB = False
    169
    170        TRANSFORMS = {
    171            **generator.Generator.TRANSFORMS,
    172            exp.ApproxDistinct: approx_count_distinct_sql,
    173            exp.Array: lambda self, e: self.func("ARRAY", e.expressions[0])
    174            if isinstance(seq_get(e.expressions, 0), exp.Select)
    175            else rename_func("LIST_VALUE")(self, e),
    176            exp.ArraySize: rename_func("ARRAY_LENGTH"),
    177            exp.ArraySort: _array_sort_sql,
    178            exp.ArraySum: rename_func("LIST_SUM"),
    179            exp.CommentColumnConstraint: no_comment_column_constraint_sql,
    180            exp.CurrentDate: lambda self, e: "CURRENT_DATE",
    181            exp.CurrentTime: lambda self, e: "CURRENT_TIME",
    182            exp.CurrentTimestamp: lambda self, e: "CURRENT_TIMESTAMP",
    183            exp.DayOfMonth: rename_func("DAYOFMONTH"),
    184            exp.DayOfWeek: rename_func("DAYOFWEEK"),
    185            exp.DayOfYear: rename_func("DAYOFYEAR"),
    186            exp.DataType: _datatype_sql,
    187            exp.DateAdd: _date_add_sql,
    188            exp.DateDiff: lambda self, e: self.func(
    189                "DATE_DIFF", f"'{e.args.get('unit', 'day')}'", e.expression, e.this
    190            ),
    191            exp.DateStrToDate: datestrtodate_sql,
    192            exp.DateToDi: lambda self, e: f"CAST(STRFTIME({self.sql(e, 'this')}, {DuckDB.dateint_format}) AS INT)",
    193            exp.DiToDate: lambda self, e: f"CAST(STRPTIME(CAST({self.sql(e, 'this')} AS TEXT), {DuckDB.dateint_format}) AS DATE)",
    194            exp.Explode: rename_func("UNNEST"),
    195            exp.IntDiv: lambda self, e: self.binary(e, "//"),
    196            exp.JSONExtract: arrow_json_extract_sql,
    197            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    198            exp.JSONBExtract: arrow_json_extract_sql,
    199            exp.JSONBExtractScalar: arrow_json_extract_scalar_sql,
    200            exp.LogicalOr: rename_func("BOOL_OR"),
    201            exp.LogicalAnd: rename_func("BOOL_AND"),
    202            exp.Properties: no_properties_sql,
    203            exp.RegexpExtract: _regexp_extract_sql,
    204            exp.RegexpLike: rename_func("REGEXP_MATCHES"),
    205            exp.RegexpSplit: rename_func("STR_SPLIT_REGEX"),
    206            exp.SafeDivide: no_safe_divide_sql,
    207            exp.Split: rename_func("STR_SPLIT"),
    208            exp.SortArray: _sort_array_sql,
    209            exp.StrPosition: str_position_sql,
    210            exp.StrToDate: lambda self, e: f"CAST({str_to_time_sql(self, e)} AS DATE)",
    211            exp.StrToTime: str_to_time_sql,
    212            exp.StrToUnix: lambda self, e: f"EPOCH(STRPTIME({self.sql(e, 'this')}, {self.format_time(e)}))",
    213            exp.Struct: _struct_sql,
    214            exp.TimestampTrunc: timestamptrunc_sql,
    215            exp.TimeStrToDate: lambda self, e: f"CAST({self.sql(e, 'this')} AS DATE)",
    216            exp.TimeStrToTime: timestrtotime_sql,
    217            exp.TimeStrToUnix: lambda self, e: f"EPOCH(CAST({self.sql(e, 'this')} AS TIMESTAMP))",
    218            exp.TimeToStr: lambda self, e: f"STRFTIME({self.sql(e, 'this')}, {self.format_time(e)})",
    219            exp.TimeToUnix: rename_func("EPOCH"),
    220            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS TEXT), '-', ''), 1, 8) AS INT)",
    221            exp.TsOrDsAdd: _ts_or_ds_add_sql,
    222            exp.TsOrDsToDate: ts_or_ds_to_date_sql("duckdb"),
    223            exp.UnixToStr: lambda self, e: f"STRFTIME(TO_TIMESTAMP({self.sql(e, 'this')}), {self.format_time(e)})",
    224            exp.UnixToTime: rename_func("TO_TIMESTAMP"),
    225            exp.UnixToTimeStr: lambda self, e: f"CAST(TO_TIMESTAMP({self.sql(e, 'this')}) AS TEXT)",
    226            exp.WeekOfYear: rename_func("WEEKOFYEAR"),
    227        }
    228
    229        TYPE_MAPPING = {
    230            **generator.Generator.TYPE_MAPPING,
    231            exp.DataType.Type.BINARY: "BLOB",
    232            exp.DataType.Type.CHAR: "TEXT",
    233            exp.DataType.Type.FLOAT: "REAL",
    234            exp.DataType.Type.NCHAR: "TEXT",
    235            exp.DataType.Type.NVARCHAR: "TEXT",
    236            exp.DataType.Type.UINT: "UINTEGER",
    237            exp.DataType.Type.VARBINARY: "BLOB",
    238            exp.DataType.Type.VARCHAR: "TEXT",
    239        }
    240
    241        STAR_MAPPING = {**generator.Generator.STAR_MAPPING, "except": "EXCLUDE"}
    242
    243        PROPERTIES_LOCATION = {
    244            **generator.Generator.PROPERTIES_LOCATION,
    245            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    246        }
    247
    248        def tablesample_sql(
    249            self, expression: exp.TableSample, seed_prefix: str = "SEED", sep: str = " AS "
    250        ) -> str:
    251            return super().tablesample_sql(expression, seed_prefix="REPEATABLE", sep=sep)

Generator interprets the given syntax tree and produces a SQL string as an output.

###### Arguments:

- time_mapping (dict): the dictionary of custom time mappings in which the key represents a python time format and the output the target time format
- time_trie (trie): a trie of the time_mapping keys
- pretty (bool): if set to True the returned string will be formatted. Default: False.
- quote_start (str): specifies which starting character to use to delimit quotes. Default: '.
- quote_end (str): specifies which ending character to use to delimit quotes. Default: '.
- identifier_start (str): specifies which starting character to use to delimit identifiers. Default: ".
- identifier_end (str): specifies which ending character to use to delimit identifiers. Default: ".
- bit_start (str): specifies which starting character to use to delimit bit literals. Default: None.
- bit_end (str): specifies which ending character to use to delimit bit literals. Default: None.
- hex_start (str): specifies which starting character to use to delimit hex literals. Default: None.
- hex_end (str): specifies which ending character to use to delimit hex literals. Default: None.
- byte_start (str): specifies which starting character to use to delimit byte literals. Default: None.
- byte_end (str): specifies which ending character to use to delimit byte literals. Default: None.
- raw_start (str): specifies which starting character to use to delimit raw literals. Default: None.
- raw_end (str): specifies which ending character to use to delimit raw literals. Default: None.
- identify (bool | str): 'always': always quote, 'safe': quote identifiers if they don't contain an upcase, True defaults to always.
- normalize (bool): if set to True all identifiers will lower cased
- string_escape (str): specifies a string escape character. Default: '.
- identifier_escape (str): specifies an identifier escape character. Default: ".
- pad (int): determines padding in a formatted string. Default: 2.
- indent (int): determines the size of indentation in a formatted string. Default: 4.
- unnest_column_only (bool): if true unnest table aliases are considered only as column aliases
- normalize_functions (str): normalize function names, "upper", "lower", or None Default: "upper"
- alias_post_tablesample (bool): if the table alias comes after tablesample Default: False
- unsupported_level (ErrorLevel): determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- null_ordering (str): Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
- max_unsupported (int): 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 (bool): if the the comma is leading or trailing in select statements 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 or not to preserve comments in the output SQL code. Default: True

def tablesample_sql( self, expression: sqlglot.expressions.TableSample, seed_prefix: str = 'SEED', sep: str = ' AS ') -> str: View Source

    248        def tablesample_sql(
    249            self, expression: exp.TableSample, seed_prefix: str = "SEED", sep: str = " AS "
    250        ) -> str:
    251            return super().tablesample_sql(expression, seed_prefix="REPEATABLE", sep=sep)

##### Inherited Members

sqlglot.generator.Generator
  Generator
  generate
  unsupported
  sep
  seg
  pad_comment
  maybe_comment
  wrap
  no_identify
  normalize_func
  indent
  sql
  uncache_sql
  cache_sql
  characterset_sql
  column_sql
  columnposition_sql
  columndef_sql
  columnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  create_sql
  clone_sql
  describe_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  bytestring_sql
  rawstring_sql
  datatypesize_sql
  datatype_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  identifier_sql
  inputoutputformat_sql
  national_sql
  partition_sql
  properties_sql
  root_properties
  properties
  with_properties
  locate_properties
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  pseudotype_sql
  onconflict_sql
  returning_sql
  rowformatdelimitedproperty_sql
  table_sql
  pivot_sql
  tuple_sql
  update_sql
  values_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_sql
  join_sql
  lambda_sql
  lateral_sql
  limit_sql
  offset_sql
  setitem_sql
  set_sql
  pragma_sql
  lock_sql
  literal_sql
  loaddata_sql
  null_sql
  boolean_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  after_having_modifiers
  after_limit_modifiers
  select_sql
  schema_sql
  star_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  windowspec_sql
  withingroup_sql
  between_sql
  bracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  constraint_sql
  nextvaluefor_sql
  extract_sql
  trim_sql
  concat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  unique_sql
  if_sql
  matchagainst_sql
  jsonkeyvalue_sql
  jsonobject_sql
  openjsoncolumndef_sql
  openjson_sql
  in_sql
  in_unnest_op
  interval_sql
  return_sql
  reference_sql
  anonymous_sql
  paren_sql
  neg_sql
  not_sql
  alias_sql
  aliases_sql
  attimezone_sql
  add_sql
  and_sql
  connector_sql
  bitwiseand_sql
  bitwiseleftshift_sql
  bitwisenot_sql
  bitwiseor_sql
  bitwiserightshift_sql
  bitwisexor_sql
  cast_sql
  currentdate_sql
  collate_sql
  command_sql
  comment_sql
  mergetreettlaction_sql
  mergetreettl_sql
  transaction_sql
  commit_sql
  rollback_sql
  altercolumn_sql
  renametable_sql
  altertable_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  div_sql
  overlaps_sql
  distance_sql
  dot_sql
  eq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  ilikeany_sql
  is_sql
  like_sql
  likeany_sql
  similarto_sql
  lt_sql
  lte_sql
  mod_sql
  mul_sql
  neq_sql
  nullsafeeq_sql
  nullsafeneq_sql
  or_sql
  slice_sql
  sub_sql
  trycast_sql
  use_sql
  binary
  function_fallback_sql
  func
  format_args
  text_width
  format_time
  expressions
  op_expressions
  naked_property
  set_operation
  tag_sql
  token_sql
  userdefinedfunction_sql
  joinhint_sql
  kwarg_sql
  when_sql
  merge_sql
  tochar_sql