Edit on GitHub

sqlglot.dialects.duckdb

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

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"
class DuckDB.Generator(sqlglot.generator.Generator):
143    class Generator(generator.Generator):
144        JOIN_HINTS = False
145        TABLE_HINTS = False
146        STRUCT_DELIMITER = ("(", ")")
147
148        TRANSFORMS = {
149            **generator.Generator.TRANSFORMS,  # type: ignore
150            exp.ApproxDistinct: approx_count_distinct_sql,
151            exp.Array: lambda self, e: self.func("ARRAY", e.expressions[0])
152            if isinstance(seq_get(e.expressions, 0), exp.Select)
153            else rename_func("LIST_VALUE")(self, e),
154            exp.ArraySize: rename_func("ARRAY_LENGTH"),
155            exp.ArraySort: _array_sort_sql,
156            exp.ArraySum: rename_func("LIST_SUM"),
157            exp.CommentColumnConstraint: no_comment_column_constraint_sql,
158            exp.DayOfMonth: rename_func("DAYOFMONTH"),
159            exp.DayOfWeek: rename_func("DAYOFWEEK"),
160            exp.DayOfYear: rename_func("DAYOFYEAR"),
161            exp.DataType: _datatype_sql,
162            exp.DateAdd: _date_add,
163            exp.DateDiff: lambda self, e: self.func(
164                "DATE_DIFF", e.args.get("unit") or exp.Literal.string("day"), e.expression, e.this
165            ),
166            exp.DateStrToDate: datestrtodate_sql,
167            exp.DateToDi: lambda self, e: f"CAST(STRFTIME({self.sql(e, 'this')}, {DuckDB.dateint_format}) AS INT)",
168            exp.DiToDate: lambda self, e: f"CAST(STRPTIME(CAST({self.sql(e, 'this')} AS TEXT), {DuckDB.dateint_format}) AS DATE)",
169            exp.Explode: rename_func("UNNEST"),
170            exp.JSONExtract: arrow_json_extract_sql,
171            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
172            exp.JSONBExtract: arrow_json_extract_sql,
173            exp.JSONBExtractScalar: arrow_json_extract_scalar_sql,
174            exp.LogicalOr: rename_func("BOOL_OR"),
175            exp.LogicalAnd: rename_func("BOOL_AND"),
176            exp.Pivot: no_pivot_sql,
177            exp.Properties: no_properties_sql,
178            exp.RegexpExtract: _regexp_extract_sql,
179            exp.RegexpLike: rename_func("REGEXP_MATCHES"),
180            exp.RegexpSplit: rename_func("STR_SPLIT_REGEX"),
181            exp.SafeDivide: no_safe_divide_sql,
182            exp.Split: rename_func("STR_SPLIT"),
183            exp.SortArray: _sort_array_sql,
184            exp.StrPosition: str_position_sql,
185            exp.StrToDate: lambda self, e: f"CAST({str_to_time_sql(self, e)} AS DATE)",
186            exp.StrToTime: str_to_time_sql,
187            exp.StrToUnix: lambda self, e: f"EPOCH(STRPTIME({self.sql(e, 'this')}, {self.format_time(e)}))",
188            exp.Struct: _struct_sql,
189            exp.TimestampTrunc: timestamptrunc_sql,
190            exp.TimeStrToDate: lambda self, e: f"CAST({self.sql(e, 'this')} AS DATE)",
191            exp.TimeStrToTime: timestrtotime_sql,
192            exp.TimeStrToUnix: lambda self, e: f"EPOCH(CAST({self.sql(e, 'this')} AS TIMESTAMP))",
193            exp.TimeToStr: lambda self, e: f"STRFTIME({self.sql(e, 'this')}, {self.format_time(e)})",
194            exp.TimeToUnix: rename_func("EPOCH"),
195            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS TEXT), '-', ''), 1, 8) AS INT)",
196            exp.TsOrDsAdd: _ts_or_ds_add,
197            exp.TsOrDsToDate: ts_or_ds_to_date_sql("duckdb"),
198            exp.UnixToStr: lambda self, e: f"STRFTIME(TO_TIMESTAMP({self.sql(e, 'this')}), {self.format_time(e)})",
199            exp.UnixToTime: rename_func("TO_TIMESTAMP"),
200            exp.UnixToTimeStr: lambda self, e: f"CAST(TO_TIMESTAMP({self.sql(e, 'this')}) AS TEXT)",
201            exp.WeekOfYear: rename_func("WEEKOFYEAR"),
202        }
203
204        TYPE_MAPPING = {
205            **generator.Generator.TYPE_MAPPING,  # type: ignore
206            exp.DataType.Type.BINARY: "BLOB",
207            exp.DataType.Type.CHAR: "TEXT",
208            exp.DataType.Type.FLOAT: "REAL",
209            exp.DataType.Type.NCHAR: "TEXT",
210            exp.DataType.Type.NVARCHAR: "TEXT",
211            exp.DataType.Type.UINT: "UINTEGER",
212            exp.DataType.Type.VARBINARY: "BLOB",
213            exp.DataType.Type.VARCHAR: "TEXT",
214        }
215
216        STAR_MAPPING = {
217            **generator.Generator.STAR_MAPPING,
218            "except": "EXCLUDE",
219        }
220
221        PROPERTIES_LOCATION = {
222            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
223            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
224        }
225
226        LIMIT_FETCH = "LIMIT"
227
228        def tablesample_sql(self, expression: exp.TableSample, seed_prefix: str = "SEED") -> str:
229            return super().tablesample_sql(expression, seed_prefix="REPEATABLE")

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: ".
  • 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') -> str:
228        def tablesample_sql(self, expression: exp.TableSample, seed_prefix: str = "SEED") -> str:
229            return super().tablesample_sql(expression, seed_prefix="REPEATABLE")
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
describe_sql
prepend_ctes
with_sql
cte_sql
tablealias_sql
bitstring_sql
hexstring_sql
bytestring_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
afterjournalproperty_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
select_sql
schema_sql
star_sql
structkwarg_sql
parameter_sql
sessionparameter_sql
placeholder_sql
subquery_sql
qualify_sql
union_sql
union_op
unnest_sql
where_sql
window_sql
partition_by_sql
window_spec_sql
withingroup_sql
between_sql
bracket_sql
all_sql
any_sql
exists_sql
case_sql
constraint_sql
extract_sql
trim_sql
concat_sql
check_sql
foreignkey_sql
primarykey_sql
unique_sql
if_sql
matchagainst_sql
jsonkeyvalue_sql
jsonobject_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
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