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_pivot_sql,
 12    no_properties_sql,
 13    no_safe_divide_sql,
 14    no_tablesample_sql,
 15    rename_func,
 16    str_position_sql,
 17    timestrtotime_sql,
 18)
 19from sqlglot.helper import seq_get
 20from sqlglot.tokens import TokenType
 21
 22
 23def _str_to_time_sql(self, expression):
 24    return f"STRPTIME({self.sql(expression, 'this')}, {self.format_time(expression)})"
 25
 26
 27def _ts_or_ds_add(self, expression):
 28    this = expression.args.get("this")
 29    unit = self.sql(expression, "unit").strip("'") or "DAY"
 30    return f"CAST({this} AS DATE) + {self.sql(exp.Interval(this=expression.expression, unit=unit))}"
 31
 32
 33def _ts_or_ds_to_date_sql(self, expression):
 34    time_format = self.format_time(expression)
 35    if time_format and time_format not in (DuckDB.time_format, DuckDB.date_format):
 36        return f"CAST({_str_to_time_sql(self, expression)} AS DATE)"
 37    return f"CAST({self.sql(expression, 'this')} AS DATE)"
 38
 39
 40def _date_add(self, expression):
 41    this = self.sql(expression, "this")
 42    unit = self.sql(expression, "unit").strip("'") or "DAY"
 43    return f"{this} + {self.sql(exp.Interval(this=expression.expression, unit=unit))}"
 44
 45
 46def _array_sort_sql(self, expression):
 47    if expression.expression:
 48        self.unsupported("DUCKDB ARRAY_SORT does not support a comparator")
 49    return f"ARRAY_SORT({self.sql(expression, 'this')})"
 50
 51
 52def _sort_array_sql(self, expression):
 53    this = self.sql(expression, "this")
 54    if expression.args.get("asc") == exp.false():
 55        return f"ARRAY_REVERSE_SORT({this})"
 56    return f"ARRAY_SORT({this})"
 57
 58
 59def _sort_array_reverse(args):
 60    return exp.SortArray(this=seq_get(args, 0), asc=exp.false())
 61
 62
 63def _struct_sql(self, expression):
 64    args = [
 65        f"'{e.name or e.this.name}': {self.sql(e, 'expression')}" for e in expression.expressions
 66    ]
 67    return f"{{{', '.join(args)}}}"
 68
 69
 70def _datatype_sql(self, expression):
 71    if expression.this == exp.DataType.Type.ARRAY:
 72        return f"{self.expressions(expression, flat=True)}[]"
 73    return self.datatype_sql(expression)
 74
 75
 76def _regexp_extract_sql(self, expression):
 77    bad_args = list(filter(expression.args.get, ("position", "occurrence")))
 78    if bad_args:
 79        self.unsupported(f"REGEXP_EXTRACT does not support arg(s) {bad_args}")
 80    return self.func(
 81        "REGEXP_EXTRACT",
 82        expression.args.get("this"),
 83        expression.args.get("expression"),
 84        expression.args.get("group"),
 85    )
 86
 87
 88class DuckDB(Dialect):
 89    class Tokenizer(tokens.Tokenizer):
 90        KEYWORDS = {
 91            **tokens.Tokenizer.KEYWORDS,
 92            ":=": TokenType.EQ,
 93            "ATTACH": TokenType.COMMAND,
 94            "CHARACTER VARYING": TokenType.VARCHAR,
 95        }
 96
 97    class Parser(parser.Parser):
 98        FUNCTIONS = {
 99            **parser.Parser.FUNCTIONS,  # type: ignore
100            "APPROX_COUNT_DISTINCT": exp.ApproxDistinct.from_arg_list,
101            "ARRAY_LENGTH": exp.ArraySize.from_arg_list,
102            "ARRAY_SORT": exp.SortArray.from_arg_list,
103            "ARRAY_REVERSE_SORT": _sort_array_reverse,
104            "EPOCH": exp.TimeToUnix.from_arg_list,
105            "EPOCH_MS": lambda args: exp.UnixToTime(
106                this=exp.Div(
107                    this=seq_get(args, 0),
108                    expression=exp.Literal.number(1000),
109                )
110            ),
111            "LIST_SORT": exp.SortArray.from_arg_list,
112            "LIST_REVERSE_SORT": _sort_array_reverse,
113            "LIST_VALUE": exp.Array.from_arg_list,
114            "REGEXP_MATCHES": exp.RegexpLike.from_arg_list,
115            "STRFTIME": format_time_lambda(exp.TimeToStr, "duckdb"),
116            "STRPTIME": format_time_lambda(exp.StrToTime, "duckdb"),
117            "STR_SPLIT": exp.Split.from_arg_list,
118            "STRING_SPLIT": exp.Split.from_arg_list,
119            "STRING_TO_ARRAY": exp.Split.from_arg_list,
120            "STR_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
121            "STRING_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
122            "STRUCT_PACK": exp.Struct.from_arg_list,
123            "TO_TIMESTAMP": exp.UnixToTime.from_arg_list,
124            "UNNEST": exp.Explode.from_arg_list,
125        }
126
127    class Generator(generator.Generator):
128        STRUCT_DELIMITER = ("(", ")")
129
130        TRANSFORMS = {
131            **generator.Generator.TRANSFORMS,  # type: ignore
132            exp.ApproxDistinct: approx_count_distinct_sql,
133            exp.Array: lambda self, e: self.func("ARRAY", e.expressions[0])
134            if isinstance(seq_get(e.expressions, 0), exp.Select)
135            else rename_func("LIST_VALUE")(self, e),
136            exp.ArraySize: rename_func("ARRAY_LENGTH"),
137            exp.ArraySort: _array_sort_sql,
138            exp.ArraySum: rename_func("LIST_SUM"),
139            exp.DataType: _datatype_sql,
140            exp.DateAdd: _date_add,
141            exp.DateDiff: lambda self, e: self.func(
142                "DATE_DIFF", e.args.get("unit") or exp.Literal.string("day"), e.expression, e.this
143            ),
144            exp.DateStrToDate: datestrtodate_sql,
145            exp.DateToDi: lambda self, e: f"CAST(STRFTIME({self.sql(e, 'this')}, {DuckDB.dateint_format}) AS INT)",
146            exp.DiToDate: lambda self, e: f"CAST(STRPTIME(CAST({self.sql(e, 'this')} AS TEXT), {DuckDB.dateint_format}) AS DATE)",
147            exp.Explode: rename_func("UNNEST"),
148            exp.JSONExtract: arrow_json_extract_sql,
149            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
150            exp.JSONBExtract: arrow_json_extract_sql,
151            exp.JSONBExtractScalar: arrow_json_extract_scalar_sql,
152            exp.LogicalOr: rename_func("BOOL_OR"),
153            exp.Pivot: no_pivot_sql,
154            exp.Properties: no_properties_sql,
155            exp.RegexpExtract: _regexp_extract_sql,
156            exp.RegexpLike: rename_func("REGEXP_MATCHES"),
157            exp.RegexpSplit: rename_func("STR_SPLIT_REGEX"),
158            exp.SafeDivide: no_safe_divide_sql,
159            exp.Split: rename_func("STR_SPLIT"),
160            exp.SortArray: _sort_array_sql,
161            exp.StrPosition: str_position_sql,
162            exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)",
163            exp.StrToTime: _str_to_time_sql,
164            exp.StrToUnix: lambda self, e: f"EPOCH(STRPTIME({self.sql(e, 'this')}, {self.format_time(e)}))",
165            exp.Struct: _struct_sql,
166            exp.TableSample: no_tablesample_sql,
167            exp.TimeStrToDate: lambda self, e: f"CAST({self.sql(e, 'this')} AS DATE)",
168            exp.TimeStrToTime: timestrtotime_sql,
169            exp.TimeStrToUnix: lambda self, e: f"EPOCH(CAST({self.sql(e, 'this')} AS TIMESTAMP))",
170            exp.TimeToStr: lambda self, e: f"STRFTIME({self.sql(e, 'this')}, {self.format_time(e)})",
171            exp.TimeToUnix: rename_func("EPOCH"),
172            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS TEXT), '-', ''), 1, 8) AS INT)",
173            exp.TsOrDsAdd: _ts_or_ds_add,
174            exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
175            exp.UnixToStr: lambda self, e: f"STRFTIME(TO_TIMESTAMP({self.sql(e, 'this')}), {self.format_time(e)})",
176            exp.UnixToTime: rename_func("TO_TIMESTAMP"),
177            exp.UnixToTimeStr: lambda self, e: f"CAST(TO_TIMESTAMP({self.sql(e, 'this')}) AS TEXT)",
178        }
179
180        TYPE_MAPPING = {
181            **generator.Generator.TYPE_MAPPING,  # type: ignore
182            exp.DataType.Type.VARCHAR: "TEXT",
183            exp.DataType.Type.NVARCHAR: "TEXT",
184        }
class DuckDB(sqlglot.dialects.dialect.Dialect):
 89class DuckDB(Dialect):
 90    class Tokenizer(tokens.Tokenizer):
 91        KEYWORDS = {
 92            **tokens.Tokenizer.KEYWORDS,
 93            ":=": TokenType.EQ,
 94            "ATTACH": TokenType.COMMAND,
 95            "CHARACTER VARYING": TokenType.VARCHAR,
 96        }
 97
 98    class Parser(parser.Parser):
 99        FUNCTIONS = {
100            **parser.Parser.FUNCTIONS,  # type: ignore
101            "APPROX_COUNT_DISTINCT": exp.ApproxDistinct.from_arg_list,
102            "ARRAY_LENGTH": exp.ArraySize.from_arg_list,
103            "ARRAY_SORT": exp.SortArray.from_arg_list,
104            "ARRAY_REVERSE_SORT": _sort_array_reverse,
105            "EPOCH": exp.TimeToUnix.from_arg_list,
106            "EPOCH_MS": lambda args: exp.UnixToTime(
107                this=exp.Div(
108                    this=seq_get(args, 0),
109                    expression=exp.Literal.number(1000),
110                )
111            ),
112            "LIST_SORT": exp.SortArray.from_arg_list,
113            "LIST_REVERSE_SORT": _sort_array_reverse,
114            "LIST_VALUE": exp.Array.from_arg_list,
115            "REGEXP_MATCHES": exp.RegexpLike.from_arg_list,
116            "STRFTIME": format_time_lambda(exp.TimeToStr, "duckdb"),
117            "STRPTIME": format_time_lambda(exp.StrToTime, "duckdb"),
118            "STR_SPLIT": exp.Split.from_arg_list,
119            "STRING_SPLIT": exp.Split.from_arg_list,
120            "STRING_TO_ARRAY": exp.Split.from_arg_list,
121            "STR_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
122            "STRING_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
123            "STRUCT_PACK": exp.Struct.from_arg_list,
124            "TO_TIMESTAMP": exp.UnixToTime.from_arg_list,
125            "UNNEST": exp.Explode.from_arg_list,
126        }
127
128    class Generator(generator.Generator):
129        STRUCT_DELIMITER = ("(", ")")
130
131        TRANSFORMS = {
132            **generator.Generator.TRANSFORMS,  # type: ignore
133            exp.ApproxDistinct: approx_count_distinct_sql,
134            exp.Array: lambda self, e: self.func("ARRAY", e.expressions[0])
135            if isinstance(seq_get(e.expressions, 0), exp.Select)
136            else rename_func("LIST_VALUE")(self, e),
137            exp.ArraySize: rename_func("ARRAY_LENGTH"),
138            exp.ArraySort: _array_sort_sql,
139            exp.ArraySum: rename_func("LIST_SUM"),
140            exp.DataType: _datatype_sql,
141            exp.DateAdd: _date_add,
142            exp.DateDiff: lambda self, e: self.func(
143                "DATE_DIFF", e.args.get("unit") or exp.Literal.string("day"), e.expression, e.this
144            ),
145            exp.DateStrToDate: datestrtodate_sql,
146            exp.DateToDi: lambda self, e: f"CAST(STRFTIME({self.sql(e, 'this')}, {DuckDB.dateint_format}) AS INT)",
147            exp.DiToDate: lambda self, e: f"CAST(STRPTIME(CAST({self.sql(e, 'this')} AS TEXT), {DuckDB.dateint_format}) AS DATE)",
148            exp.Explode: rename_func("UNNEST"),
149            exp.JSONExtract: arrow_json_extract_sql,
150            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
151            exp.JSONBExtract: arrow_json_extract_sql,
152            exp.JSONBExtractScalar: arrow_json_extract_scalar_sql,
153            exp.LogicalOr: rename_func("BOOL_OR"),
154            exp.Pivot: no_pivot_sql,
155            exp.Properties: no_properties_sql,
156            exp.RegexpExtract: _regexp_extract_sql,
157            exp.RegexpLike: rename_func("REGEXP_MATCHES"),
158            exp.RegexpSplit: rename_func("STR_SPLIT_REGEX"),
159            exp.SafeDivide: no_safe_divide_sql,
160            exp.Split: rename_func("STR_SPLIT"),
161            exp.SortArray: _sort_array_sql,
162            exp.StrPosition: str_position_sql,
163            exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)",
164            exp.StrToTime: _str_to_time_sql,
165            exp.StrToUnix: lambda self, e: f"EPOCH(STRPTIME({self.sql(e, 'this')}, {self.format_time(e)}))",
166            exp.Struct: _struct_sql,
167            exp.TableSample: no_tablesample_sql,
168            exp.TimeStrToDate: lambda self, e: f"CAST({self.sql(e, 'this')} AS DATE)",
169            exp.TimeStrToTime: timestrtotime_sql,
170            exp.TimeStrToUnix: lambda self, e: f"EPOCH(CAST({self.sql(e, 'this')} AS TIMESTAMP))",
171            exp.TimeToStr: lambda self, e: f"STRFTIME({self.sql(e, 'this')}, {self.format_time(e)})",
172            exp.TimeToUnix: rename_func("EPOCH"),
173            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS TEXT), '-', ''), 1, 8) AS INT)",
174            exp.TsOrDsAdd: _ts_or_ds_add,
175            exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
176            exp.UnixToStr: lambda self, e: f"STRFTIME(TO_TIMESTAMP({self.sql(e, 'this')}), {self.format_time(e)})",
177            exp.UnixToTime: rename_func("TO_TIMESTAMP"),
178            exp.UnixToTimeStr: lambda self, e: f"CAST(TO_TIMESTAMP({self.sql(e, 'this')}) AS TEXT)",
179        }
180
181        TYPE_MAPPING = {
182            **generator.Generator.TYPE_MAPPING,  # type: ignore
183            exp.DataType.Type.VARCHAR: "TEXT",
184            exp.DataType.Type.NVARCHAR: "TEXT",
185        }
DuckDB()
class DuckDB.Tokenizer(sqlglot.tokens.Tokenizer):
90    class Tokenizer(tokens.Tokenizer):
91        KEYWORDS = {
92            **tokens.Tokenizer.KEYWORDS,
93            ":=": TokenType.EQ,
94            "ATTACH": TokenType.COMMAND,
95            "CHARACTER VARYING": TokenType.VARCHAR,
96        }
class DuckDB.Parser(sqlglot.parser.Parser):
 98    class Parser(parser.Parser):
 99        FUNCTIONS = {
100            **parser.Parser.FUNCTIONS,  # type: ignore
101            "APPROX_COUNT_DISTINCT": exp.ApproxDistinct.from_arg_list,
102            "ARRAY_LENGTH": exp.ArraySize.from_arg_list,
103            "ARRAY_SORT": exp.SortArray.from_arg_list,
104            "ARRAY_REVERSE_SORT": _sort_array_reverse,
105            "EPOCH": exp.TimeToUnix.from_arg_list,
106            "EPOCH_MS": lambda args: exp.UnixToTime(
107                this=exp.Div(
108                    this=seq_get(args, 0),
109                    expression=exp.Literal.number(1000),
110                )
111            ),
112            "LIST_SORT": exp.SortArray.from_arg_list,
113            "LIST_REVERSE_SORT": _sort_array_reverse,
114            "LIST_VALUE": exp.Array.from_arg_list,
115            "REGEXP_MATCHES": exp.RegexpLike.from_arg_list,
116            "STRFTIME": format_time_lambda(exp.TimeToStr, "duckdb"),
117            "STRPTIME": format_time_lambda(exp.StrToTime, "duckdb"),
118            "STR_SPLIT": exp.Split.from_arg_list,
119            "STRING_SPLIT": exp.Split.from_arg_list,
120            "STRING_TO_ARRAY": exp.Split.from_arg_list,
121            "STR_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
122            "STRING_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
123            "STRUCT_PACK": exp.Struct.from_arg_list,
124            "TO_TIMESTAMP": exp.UnixToTime.from_arg_list,
125            "UNNEST": exp.Explode.from_arg_list,
126        }

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):
128    class Generator(generator.Generator):
129        STRUCT_DELIMITER = ("(", ")")
130
131        TRANSFORMS = {
132            **generator.Generator.TRANSFORMS,  # type: ignore
133            exp.ApproxDistinct: approx_count_distinct_sql,
134            exp.Array: lambda self, e: self.func("ARRAY", e.expressions[0])
135            if isinstance(seq_get(e.expressions, 0), exp.Select)
136            else rename_func("LIST_VALUE")(self, e),
137            exp.ArraySize: rename_func("ARRAY_LENGTH"),
138            exp.ArraySort: _array_sort_sql,
139            exp.ArraySum: rename_func("LIST_SUM"),
140            exp.DataType: _datatype_sql,
141            exp.DateAdd: _date_add,
142            exp.DateDiff: lambda self, e: self.func(
143                "DATE_DIFF", e.args.get("unit") or exp.Literal.string("day"), e.expression, e.this
144            ),
145            exp.DateStrToDate: datestrtodate_sql,
146            exp.DateToDi: lambda self, e: f"CAST(STRFTIME({self.sql(e, 'this')}, {DuckDB.dateint_format}) AS INT)",
147            exp.DiToDate: lambda self, e: f"CAST(STRPTIME(CAST({self.sql(e, 'this')} AS TEXT), {DuckDB.dateint_format}) AS DATE)",
148            exp.Explode: rename_func("UNNEST"),
149            exp.JSONExtract: arrow_json_extract_sql,
150            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
151            exp.JSONBExtract: arrow_json_extract_sql,
152            exp.JSONBExtractScalar: arrow_json_extract_scalar_sql,
153            exp.LogicalOr: rename_func("BOOL_OR"),
154            exp.Pivot: no_pivot_sql,
155            exp.Properties: no_properties_sql,
156            exp.RegexpExtract: _regexp_extract_sql,
157            exp.RegexpLike: rename_func("REGEXP_MATCHES"),
158            exp.RegexpSplit: rename_func("STR_SPLIT_REGEX"),
159            exp.SafeDivide: no_safe_divide_sql,
160            exp.Split: rename_func("STR_SPLIT"),
161            exp.SortArray: _sort_array_sql,
162            exp.StrPosition: str_position_sql,
163            exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)",
164            exp.StrToTime: _str_to_time_sql,
165            exp.StrToUnix: lambda self, e: f"EPOCH(STRPTIME({self.sql(e, 'this')}, {self.format_time(e)}))",
166            exp.Struct: _struct_sql,
167            exp.TableSample: no_tablesample_sql,
168            exp.TimeStrToDate: lambda self, e: f"CAST({self.sql(e, 'this')} AS DATE)",
169            exp.TimeStrToTime: timestrtotime_sql,
170            exp.TimeStrToUnix: lambda self, e: f"EPOCH(CAST({self.sql(e, 'this')} AS TIMESTAMP))",
171            exp.TimeToStr: lambda self, e: f"STRFTIME({self.sql(e, 'this')}, {self.format_time(e)})",
172            exp.TimeToUnix: rename_func("EPOCH"),
173            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS TEXT), '-', ''), 1, 8) AS INT)",
174            exp.TsOrDsAdd: _ts_or_ds_add,
175            exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
176            exp.UnixToStr: lambda self, e: f"STRFTIME(TO_TIMESTAMP({self.sql(e, 'this')}), {self.format_time(e)})",
177            exp.UnixToTime: rename_func("TO_TIMESTAMP"),
178            exp.UnixToTimeStr: lambda self, e: f"CAST(TO_TIMESTAMP({self.sql(e, 'this')}) AS TEXT)",
179        }
180
181        TYPE_MAPPING = {
182            **generator.Generator.TYPE_MAPPING,  # type: ignore
183            exp.DataType.Type.VARCHAR: "TEXT",
184            exp.DataType.Type.NVARCHAR: "TEXT",
185        }

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): if set to True all identifiers will be delimited by the corresponding character.
  • 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
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
columndef_sql
columnconstraint_sql
autoincrementcolumnconstraint_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
datatype_sql
directory_sql
delete_sql
drop_sql
except_sql
except_op
fetch_sql
filter_sql
hint_sql
index_sql
identifier_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
insert_sql
intersect_sql
intersect_op
introducer_sql
pseudotype_sql
rowformatdelimitedproperty_sql
table_sql
tablesample_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
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
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
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
distance_sql
dot_sql
eq_sql
escape_sql
glob_sql
gt_sql
gte_sql
ilike_sql
is_sql
like_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