sqlglot.dialects.duckdb API documentation

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

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

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

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

##### Inherited Members

sqlglot.tokens.Tokenizer
  reset
  tokenize

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

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

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

    251        def tablesample_sql(
    252            self, expression: exp.TableSample, seed_prefix: str = "SEED", sep: str = " AS "
    253        ) -> str:
    254            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
  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
  dictproperty_sql
  dictrange_sql
  dictsubproperty_sql