Edit on GitHub

sqlglot.generators.sqlite

  1from __future__ import annotations
  2
  3import typing as t
  4
  5from sqlglot import exp, generator, transforms
  6from sqlglot.dialects.dialect import (
  7    any_value_to_max_sql,
  8    arrow_json_extract_sql,
  9    concat_to_dpipe_sql,
 10    count_if_to_sum,
 11    no_ilike_sql,
 12    no_pivot_sql,
 13    no_tablesample_sql,
 14    no_trycast_sql,
 15    rename_func,
 16    strposition_sql,
 17)
 18from sqlglot.generator import unsupported_args
 19from sqlglot.optimizer.scope import find_in_scope
 20from sqlglot.tokens import TokenType
 21
 22
 23def _transform_create(expression: exp.Expr) -> exp.Expr:
 24    """Move primary key to a column and enforce auto_increment on primary keys."""
 25    schema = expression.this
 26
 27    if isinstance(expression, exp.Create) and isinstance(schema, exp.Schema):
 28        defs = {}
 29        primary_key = None
 30
 31        for e in schema.expressions:
 32            if isinstance(e, exp.ColumnDef):
 33                defs[e.name] = e
 34            elif isinstance(e, exp.PrimaryKey):
 35                primary_key = e
 36
 37        if primary_key and len(primary_key.expressions) == 1:
 38            column = defs[primary_key.expressions[0].name]
 39            column.append(
 40                "constraints", exp.ColumnConstraint(kind=exp.PrimaryKeyColumnConstraint())
 41            )
 42            schema.expressions.remove(primary_key)
 43
 44        for column in defs.values():
 45            primary_key_index = -1
 46            auto_increment = None
 47            auto_increment_index = -1
 48
 49            for i, constraint in enumerate(column.constraints):
 50                if isinstance(constraint.kind, exp.PrimaryKeyColumnConstraint):
 51                    primary_key_index = i
 52                elif isinstance(constraint.kind, exp.AutoIncrementColumnConstraint):
 53                    auto_increment = constraint
 54                    auto_increment_index = i
 55
 56            if auto_increment is not None and (
 57                primary_key_index == -1 or auto_increment_index < primary_key_index
 58            ):
 59                column.constraints.remove(auto_increment)
 60                if primary_key_index != -1:
 61                    column.constraints.insert(primary_key_index, auto_increment)
 62
 63    return expression
 64
 65
 66def _generated_to_auto_increment(expression: exp.Expr) -> exp.Expr:
 67    if not isinstance(expression, exp.ColumnDef):
 68        return expression
 69
 70    generated = expression.find(exp.GeneratedAsIdentityColumnConstraint)
 71
 72    # Only rewrite true identity columns. Expression-bearing forms are computed
 73    # columns (GENERATED ALWAYS AS (expr)) and must keep their expression.
 74    if generated and generated.expression is None:
 75        t.cast(exp.ColumnConstraint, generated.parent).pop()
 76
 77        not_null = expression.find(exp.NotNullColumnConstraint)
 78        if not_null:
 79            t.cast(exp.ColumnConstraint, not_null.parent).pop()
 80
 81        expression.append(
 82            "constraints", exp.ColumnConstraint(kind=exp.AutoIncrementColumnConstraint())
 83        )
 84
 85    return expression
 86
 87
 88def _offset_to_limit(expression: exp.Expr) -> exp.Expr:
 89    if not isinstance(expression, exp.Select):
 90        return expression
 91
 92    offset = expression.args.get("offset")
 93
 94    if offset and not expression.args.get("limit"):
 95        expression.limit(-1, copy=False)
 96
 97    return expression
 98
 99
100class SQLiteGenerator(generator.Generator):
101    SELECT_KINDS: tuple[str, ...] = ()
102    TRY_SUPPORTED = False
103    SUPPORTS_UESCAPE = False
104    SUPPORTS_DECODE_CASE = False
105
106    AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
107
108    JOIN_HINTS = False
109    TABLE_HINTS = False
110    QUERY_HINTS = False
111    NVL2_SUPPORTED = False
112    JSON_PATH_BRACKETED_KEY_SUPPORTED = False
113    SUPPORTS_CREATE_TABLE_LIKE = False
114    SUPPORTS_TABLE_ALIAS_COLUMNS = False
115    SUPPORTS_TO_NUMBER = False
116    SUPPORTS_WINDOW_EXCLUDE = True
117    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
118    SUPPORTS_MEDIAN = False
119    JSON_KEY_VALUE_PAIR_SEP = ","
120    PARSE_JSON_NAME: str | None = None
121
122    SUPPORTED_JSON_PATH_PARTS = {
123        exp.JSONPathKey,
124        exp.JSONPathRoot,
125        exp.JSONPathSubscript,
126    }
127
128    TYPE_MAPPING = {
129        **{k: v for k, v in generator.Generator.TYPE_MAPPING.items() if k != exp.DType.BLOB},
130        exp.DType.BOOLEAN: "INTEGER",
131        exp.DType.TINYINT: "INTEGER",
132        exp.DType.SMALLINT: "INTEGER",
133        exp.DType.INT: "INTEGER",
134        exp.DType.BIGINT: "INTEGER",
135        exp.DType.FLOAT: "REAL",
136        exp.DType.DOUBLE: "REAL",
137        exp.DType.DECIMAL: "REAL",
138        exp.DType.CHAR: "TEXT",
139        exp.DType.NCHAR: "TEXT",
140        exp.DType.VARCHAR: "TEXT",
141        exp.DType.NVARCHAR: "TEXT",
142        exp.DType.BINARY: "BLOB",
143        exp.DType.VARBINARY: "BLOB",
144    }
145
146    TOKEN_MAPPING = {
147        TokenType.AUTO_INCREMENT: "AUTOINCREMENT",
148    }
149
150    TRANSFORMS = {
151        **generator.Generator.TRANSFORMS,
152        exp.AnyValue: any_value_to_max_sql,
153        exp.Chr: rename_func("CHAR"),
154        exp.Concat: concat_to_dpipe_sql,
155        exp.CountIf: count_if_to_sum,
156        exp.Create: transforms.preprocess([_transform_create]),
157        exp.CurrentDate: lambda *_: "CURRENT_DATE",
158        exp.CurrentTime: lambda *_: "CURRENT_TIME",
159        exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
160        exp.CurrentVersion: lambda *_: "SQLITE_VERSION()",
161        exp.ColumnDef: transforms.preprocess([_generated_to_auto_increment]),
162        exp.DateStrToDate: lambda self, e: self.sql(e, "this"),
163        exp.If: rename_func("IIF"),
164        exp.ILike: no_ilike_sql,
165        exp.JSONArrayAgg: unsupported_args("order", "null_handling", "return_type", "strict")(
166            rename_func("JSON_GROUP_ARRAY")
167        ),
168        exp.JSONObjectAgg: lambda self, e: self._jsonobject_sql(e, name="JSON_GROUP_OBJECT"),
169        exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")(
170            rename_func("EDITDIST3")
171        ),
172        exp.LogicalOr: rename_func("MAX"),
173        exp.LogicalAnd: rename_func("MIN"),
174        exp.Pivot: no_pivot_sql,
175        exp.Rand: rename_func("RANDOM"),
176        exp.Select: transforms.preprocess(
177            [
178                _offset_to_limit,
179                transforms.eliminate_distinct_on,
180                transforms.eliminate_qualify,
181                transforms.eliminate_semi_and_anti_joins,
182            ]
183        ),
184        exp.StrPosition: lambda self, e: strposition_sql(self, e, func_name="INSTR"),
185        exp.TableSample: no_tablesample_sql,
186        exp.TimeStrToTime: lambda self, e: self.sql(e, "this"),
187        exp.TimeToStr: lambda self, e: self.func("STRFTIME", e.args.get("format"), e.this),
188        exp.TryCast: no_trycast_sql,
189        exp.TsOrDsToTimestamp: lambda self, e: self.sql(e, "this"),
190    }
191
192    # SQLite doesn't generally support CREATE TABLE .. properties
193    # https://www.sqlite.org/lang_createtable.html
194    PROPERTIES_LOCATION = {
195        **{
196            prop: exp.Properties.Location.UNSUPPORTED
197            for prop in generator.Generator.PROPERTIES_LOCATION
198        },
199        # There are a few exceptions (e.g. temporary tables) which are supported or
200        # can be transpiled to SQLite, so we explicitly override them accordingly
201        exp.LikeProperty: exp.Properties.Location.POST_SCHEMA,
202        exp.ModuleProperty: exp.Properties.Location.POST_SCHEMA,
203        exp.TemporaryProperty: exp.Properties.Location.POST_CREATE,
204        exp.VirtualProperty: exp.Properties.Location.POST_CREATE,
205    }
206
207    LIMIT_FETCH = "LIMIT"
208
209    def insert_sql(self, expression: exp.Insert) -> str:
210        if expression.args.get("ignore"):
211            expression.set("ignore", False)
212            expression.set("alternative", "IGNORE")
213
214        return super().insert_sql(expression)
215
216    def bitwiseandagg_sql(self, expression: exp.BitwiseAndAgg) -> str:
217        self.unsupported("BITWISE_AND aggregation is not supported in SQLite")
218        return self.function_fallback_sql(expression)
219
220    def bitwiseoragg_sql(self, expression: exp.BitwiseOrAgg) -> str:
221        self.unsupported("BITWISE_OR aggregation is not supported in SQLite")
222        return self.function_fallback_sql(expression)
223
224    def bitwisexoragg_sql(self, expression: exp.BitwiseXorAgg) -> str:
225        self.unsupported("BITWISE_XOR aggregation is not supported in SQLite")
226        return self.function_fallback_sql(expression)
227
228    def jsonextract_sql(self, expression: exp.JSONExtract) -> str:
229        if expression.expressions:
230            return self.function_fallback_sql(expression)
231        return arrow_json_extract_sql(self, expression)
232
233    def jsonextractscalar_sql(self, expression: exp.JSONExtractScalar) -> str:
234        if expression.args.get("json_subtype"):
235            # json_extract() keeps the JSON subtype on object/array results;
236            # ->> strips it, observable when the result feeds another JSON function
237            return self.func("JSON_EXTRACT", expression.this, expression.expression)
238        return arrow_json_extract_sql(self, expression)
239
240    def dateadd_sql(self, expression: exp.DateAdd) -> str:
241        modifier = expression.expression
242        unit = expression.args.get("unit")
243        # An INTERVAL amount carries its own unit, e.g. DATE_ADD(d, INTERVAL 1 DAY);
244        # unwrap it so the unit is not left inside the quoted modifier string.
245        if isinstance(modifier, exp.Interval):
246            unit = unit or modifier.unit
247            modifier = modifier.this
248        modifier = modifier.name if modifier.is_string else self.sql(modifier)
249        modifier = f"'{modifier} {unit.name}'" if unit else f"'{modifier}'"
250        return self.func("DATE", expression.this, modifier)
251
252    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
253        if expression.is_type("date"):
254            return self.func("DATE", expression.this)
255
256        return super().cast_sql(expression)
257
258    # https://www.sqlite.org/gencol.html
259    # Inline unsupported check: mypyc cannot compile @unsupported_args on an
260    # override of an undecorated base-class method.
261    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
262        if expression.args.get("data_type"):
263            self.unsupported("SQLite generated columns do not support a data type")
264
265        this = expression.this
266        this_sql = self.sql(this) if isinstance(this, exp.Paren) else f"({self.sql(this)})"
267        storage = " STORED" if expression.args.get("persisted") else ""
268        not_null = " NOT NULL" if expression.args.get("not_null") else ""
269        return f"AS {this_sql}{storage}{not_null}"
270
271    # Note: SQLite's TRUNC always returns REAL (e.g., trunc(10.99) -> 10.0), not INTEGER.
272    # This creates a transpilation gap affecting division semantics, similar to Presto.
273    # Unlike Presto where this only affects decimals=0, SQLite has no decimals parameter
274    # so every use of TRUNC is affected. Modeling precisely would require exp.FloatTrunc.
275    @unsupported_args("decimals")
276    def trunc_sql(self, expression: exp.Trunc) -> str:
277        return self.func("TRUNC", expression.this)
278
279    def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
280        parent = expression.parent
281        alias = parent and parent.args.get("alias")
282
283        if isinstance(alias, exp.TableAlias) and alias.columns:
284            column_alias = alias.columns[0]
285            alias.set("columns", None)
286            sql = self.sql(
287                exp.select(exp.alias_("value", column_alias)).from_(expression).subquery()
288            )
289        else:
290            sql = self.function_fallback_sql(expression)
291
292        return sql
293
294    def datediff_sql(self, expression: exp.DateDiff) -> str:
295        unit = expression.args.get("unit")
296        unit = unit.name.upper() if unit else "DAY"
297
298        sql = f"(JULIANDAY({self.sql(expression, 'this')}) - JULIANDAY({self.sql(expression, 'expression')}))"
299
300        if unit == "MONTH":
301            sql = f"{sql} / 30.0"
302        elif unit == "YEAR":
303            sql = f"{sql} / 365.0"
304        elif unit == "HOUR":
305            sql = f"{sql} * 24.0"
306        elif unit == "MINUTE":
307            sql = f"{sql} * 1440.0"
308        elif unit == "SECOND":
309            sql = f"{sql} * 86400.0"
310        elif unit == "MILLISECOND":
311            sql = f"{sql} * 86400000.0"
312        elif unit == "MICROSECOND":
313            sql = f"{sql} * 86400000000.0"
314        elif unit == "NANOSECOND":
315            sql = f"{sql} * 8640000000000.0"
316        else:
317            self.unsupported(f"DATEDIFF unsupported for '{unit}'.")
318
319        return f"CAST({sql} AS INTEGER)"
320
321    # https://www.sqlite.org/lang_aggfunc.html#group_concat
322    def groupconcat_sql(self, expression: exp.GroupConcat) -> str:
323        this = expression.this
324        distinct = find_in_scope(expression, exp.Distinct)
325
326        if distinct:
327            this = distinct.expressions[0]
328            distinct_sql = "DISTINCT "
329        else:
330            distinct_sql = ""
331
332        if isinstance(expression.this, exp.Order):
333            self.unsupported("SQLite GROUP_CONCAT doesn't support ORDER BY.")
334            if expression.this.this and not distinct:
335                this = expression.this.this
336
337        separator = expression.args.get("separator")
338        return f"GROUP_CONCAT({distinct_sql}{self.format_args(this, separator)})"
339
340    def least_sql(self, expression: exp.Least) -> str:
341        if expression.expressions:
342            return rename_func("MIN")(self, expression)
343
344        return self.sql(expression, "this")
345
346    def greatest_sql(self, expression: exp.Greatest) -> str:
347        if expression.expressions:
348            return rename_func("MAX")(self, expression)
349
350        return self.sql(expression, "this")
351
352    def transaction_sql(self, expression: exp.Transaction) -> str:
353        this = expression.this
354        this = f" {this}" if this else ""
355        return f"BEGIN{this} TRANSACTION"
356
357    def isascii_sql(self, expression: exp.IsAscii) -> str:
358        return f"(NOT {self.sql(expression.this)} GLOB CAST(x'2a5b5e012d7f5d2a' AS TEXT))"
359
360    @unsupported_args("this")
361    def currentschema_sql(self, expression: exp.CurrentSchema) -> str:
362        return "'main'"
363
364    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
365        self.unsupported("SQLite does not support IGNORE NULLS.")
366        return self.sql(expression.this)
367
368    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
369        return self.sql(expression.this)
370
371    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
372        if (
373            expression.text("kind").upper() == "RANGE"
374            and expression.text("start").upper() == "CURRENT ROW"
375        ):
376            return "RANGE CURRENT ROW"
377
378        return super().windowspec_sql(expression)
class SQLiteGenerator(sqlglot.generator.Generator):
101class SQLiteGenerator(generator.Generator):
102    SELECT_KINDS: tuple[str, ...] = ()
103    TRY_SUPPORTED = False
104    SUPPORTS_UESCAPE = False
105    SUPPORTS_DECODE_CASE = False
106
107    AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
108
109    JOIN_HINTS = False
110    TABLE_HINTS = False
111    QUERY_HINTS = False
112    NVL2_SUPPORTED = False
113    JSON_PATH_BRACKETED_KEY_SUPPORTED = False
114    SUPPORTS_CREATE_TABLE_LIKE = False
115    SUPPORTS_TABLE_ALIAS_COLUMNS = False
116    SUPPORTS_TO_NUMBER = False
117    SUPPORTS_WINDOW_EXCLUDE = True
118    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
119    SUPPORTS_MEDIAN = False
120    JSON_KEY_VALUE_PAIR_SEP = ","
121    PARSE_JSON_NAME: str | None = None
122
123    SUPPORTED_JSON_PATH_PARTS = {
124        exp.JSONPathKey,
125        exp.JSONPathRoot,
126        exp.JSONPathSubscript,
127    }
128
129    TYPE_MAPPING = {
130        **{k: v for k, v in generator.Generator.TYPE_MAPPING.items() if k != exp.DType.BLOB},
131        exp.DType.BOOLEAN: "INTEGER",
132        exp.DType.TINYINT: "INTEGER",
133        exp.DType.SMALLINT: "INTEGER",
134        exp.DType.INT: "INTEGER",
135        exp.DType.BIGINT: "INTEGER",
136        exp.DType.FLOAT: "REAL",
137        exp.DType.DOUBLE: "REAL",
138        exp.DType.DECIMAL: "REAL",
139        exp.DType.CHAR: "TEXT",
140        exp.DType.NCHAR: "TEXT",
141        exp.DType.VARCHAR: "TEXT",
142        exp.DType.NVARCHAR: "TEXT",
143        exp.DType.BINARY: "BLOB",
144        exp.DType.VARBINARY: "BLOB",
145    }
146
147    TOKEN_MAPPING = {
148        TokenType.AUTO_INCREMENT: "AUTOINCREMENT",
149    }
150
151    TRANSFORMS = {
152        **generator.Generator.TRANSFORMS,
153        exp.AnyValue: any_value_to_max_sql,
154        exp.Chr: rename_func("CHAR"),
155        exp.Concat: concat_to_dpipe_sql,
156        exp.CountIf: count_if_to_sum,
157        exp.Create: transforms.preprocess([_transform_create]),
158        exp.CurrentDate: lambda *_: "CURRENT_DATE",
159        exp.CurrentTime: lambda *_: "CURRENT_TIME",
160        exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
161        exp.CurrentVersion: lambda *_: "SQLITE_VERSION()",
162        exp.ColumnDef: transforms.preprocess([_generated_to_auto_increment]),
163        exp.DateStrToDate: lambda self, e: self.sql(e, "this"),
164        exp.If: rename_func("IIF"),
165        exp.ILike: no_ilike_sql,
166        exp.JSONArrayAgg: unsupported_args("order", "null_handling", "return_type", "strict")(
167            rename_func("JSON_GROUP_ARRAY")
168        ),
169        exp.JSONObjectAgg: lambda self, e: self._jsonobject_sql(e, name="JSON_GROUP_OBJECT"),
170        exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")(
171            rename_func("EDITDIST3")
172        ),
173        exp.LogicalOr: rename_func("MAX"),
174        exp.LogicalAnd: rename_func("MIN"),
175        exp.Pivot: no_pivot_sql,
176        exp.Rand: rename_func("RANDOM"),
177        exp.Select: transforms.preprocess(
178            [
179                _offset_to_limit,
180                transforms.eliminate_distinct_on,
181                transforms.eliminate_qualify,
182                transforms.eliminate_semi_and_anti_joins,
183            ]
184        ),
185        exp.StrPosition: lambda self, e: strposition_sql(self, e, func_name="INSTR"),
186        exp.TableSample: no_tablesample_sql,
187        exp.TimeStrToTime: lambda self, e: self.sql(e, "this"),
188        exp.TimeToStr: lambda self, e: self.func("STRFTIME", e.args.get("format"), e.this),
189        exp.TryCast: no_trycast_sql,
190        exp.TsOrDsToTimestamp: lambda self, e: self.sql(e, "this"),
191    }
192
193    # SQLite doesn't generally support CREATE TABLE .. properties
194    # https://www.sqlite.org/lang_createtable.html
195    PROPERTIES_LOCATION = {
196        **{
197            prop: exp.Properties.Location.UNSUPPORTED
198            for prop in generator.Generator.PROPERTIES_LOCATION
199        },
200        # There are a few exceptions (e.g. temporary tables) which are supported or
201        # can be transpiled to SQLite, so we explicitly override them accordingly
202        exp.LikeProperty: exp.Properties.Location.POST_SCHEMA,
203        exp.ModuleProperty: exp.Properties.Location.POST_SCHEMA,
204        exp.TemporaryProperty: exp.Properties.Location.POST_CREATE,
205        exp.VirtualProperty: exp.Properties.Location.POST_CREATE,
206    }
207
208    LIMIT_FETCH = "LIMIT"
209
210    def insert_sql(self, expression: exp.Insert) -> str:
211        if expression.args.get("ignore"):
212            expression.set("ignore", False)
213            expression.set("alternative", "IGNORE")
214
215        return super().insert_sql(expression)
216
217    def bitwiseandagg_sql(self, expression: exp.BitwiseAndAgg) -> str:
218        self.unsupported("BITWISE_AND aggregation is not supported in SQLite")
219        return self.function_fallback_sql(expression)
220
221    def bitwiseoragg_sql(self, expression: exp.BitwiseOrAgg) -> str:
222        self.unsupported("BITWISE_OR aggregation is not supported in SQLite")
223        return self.function_fallback_sql(expression)
224
225    def bitwisexoragg_sql(self, expression: exp.BitwiseXorAgg) -> str:
226        self.unsupported("BITWISE_XOR aggregation is not supported in SQLite")
227        return self.function_fallback_sql(expression)
228
229    def jsonextract_sql(self, expression: exp.JSONExtract) -> str:
230        if expression.expressions:
231            return self.function_fallback_sql(expression)
232        return arrow_json_extract_sql(self, expression)
233
234    def jsonextractscalar_sql(self, expression: exp.JSONExtractScalar) -> str:
235        if expression.args.get("json_subtype"):
236            # json_extract() keeps the JSON subtype on object/array results;
237            # ->> strips it, observable when the result feeds another JSON function
238            return self.func("JSON_EXTRACT", expression.this, expression.expression)
239        return arrow_json_extract_sql(self, expression)
240
241    def dateadd_sql(self, expression: exp.DateAdd) -> str:
242        modifier = expression.expression
243        unit = expression.args.get("unit")
244        # An INTERVAL amount carries its own unit, e.g. DATE_ADD(d, INTERVAL 1 DAY);
245        # unwrap it so the unit is not left inside the quoted modifier string.
246        if isinstance(modifier, exp.Interval):
247            unit = unit or modifier.unit
248            modifier = modifier.this
249        modifier = modifier.name if modifier.is_string else self.sql(modifier)
250        modifier = f"'{modifier} {unit.name}'" if unit else f"'{modifier}'"
251        return self.func("DATE", expression.this, modifier)
252
253    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
254        if expression.is_type("date"):
255            return self.func("DATE", expression.this)
256
257        return super().cast_sql(expression)
258
259    # https://www.sqlite.org/gencol.html
260    # Inline unsupported check: mypyc cannot compile @unsupported_args on an
261    # override of an undecorated base-class method.
262    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
263        if expression.args.get("data_type"):
264            self.unsupported("SQLite generated columns do not support a data type")
265
266        this = expression.this
267        this_sql = self.sql(this) if isinstance(this, exp.Paren) else f"({self.sql(this)})"
268        storage = " STORED" if expression.args.get("persisted") else ""
269        not_null = " NOT NULL" if expression.args.get("not_null") else ""
270        return f"AS {this_sql}{storage}{not_null}"
271
272    # Note: SQLite's TRUNC always returns REAL (e.g., trunc(10.99) -> 10.0), not INTEGER.
273    # This creates a transpilation gap affecting division semantics, similar to Presto.
274    # Unlike Presto where this only affects decimals=0, SQLite has no decimals parameter
275    # so every use of TRUNC is affected. Modeling precisely would require exp.FloatTrunc.
276    @unsupported_args("decimals")
277    def trunc_sql(self, expression: exp.Trunc) -> str:
278        return self.func("TRUNC", expression.this)
279
280    def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
281        parent = expression.parent
282        alias = parent and parent.args.get("alias")
283
284        if isinstance(alias, exp.TableAlias) and alias.columns:
285            column_alias = alias.columns[0]
286            alias.set("columns", None)
287            sql = self.sql(
288                exp.select(exp.alias_("value", column_alias)).from_(expression).subquery()
289            )
290        else:
291            sql = self.function_fallback_sql(expression)
292
293        return sql
294
295    def datediff_sql(self, expression: exp.DateDiff) -> str:
296        unit = expression.args.get("unit")
297        unit = unit.name.upper() if unit else "DAY"
298
299        sql = f"(JULIANDAY({self.sql(expression, 'this')}) - JULIANDAY({self.sql(expression, 'expression')}))"
300
301        if unit == "MONTH":
302            sql = f"{sql} / 30.0"
303        elif unit == "YEAR":
304            sql = f"{sql} / 365.0"
305        elif unit == "HOUR":
306            sql = f"{sql} * 24.0"
307        elif unit == "MINUTE":
308            sql = f"{sql} * 1440.0"
309        elif unit == "SECOND":
310            sql = f"{sql} * 86400.0"
311        elif unit == "MILLISECOND":
312            sql = f"{sql} * 86400000.0"
313        elif unit == "MICROSECOND":
314            sql = f"{sql} * 86400000000.0"
315        elif unit == "NANOSECOND":
316            sql = f"{sql} * 8640000000000.0"
317        else:
318            self.unsupported(f"DATEDIFF unsupported for '{unit}'.")
319
320        return f"CAST({sql} AS INTEGER)"
321
322    # https://www.sqlite.org/lang_aggfunc.html#group_concat
323    def groupconcat_sql(self, expression: exp.GroupConcat) -> str:
324        this = expression.this
325        distinct = find_in_scope(expression, exp.Distinct)
326
327        if distinct:
328            this = distinct.expressions[0]
329            distinct_sql = "DISTINCT "
330        else:
331            distinct_sql = ""
332
333        if isinstance(expression.this, exp.Order):
334            self.unsupported("SQLite GROUP_CONCAT doesn't support ORDER BY.")
335            if expression.this.this and not distinct:
336                this = expression.this.this
337
338        separator = expression.args.get("separator")
339        return f"GROUP_CONCAT({distinct_sql}{self.format_args(this, separator)})"
340
341    def least_sql(self, expression: exp.Least) -> str:
342        if expression.expressions:
343            return rename_func("MIN")(self, expression)
344
345        return self.sql(expression, "this")
346
347    def greatest_sql(self, expression: exp.Greatest) -> str:
348        if expression.expressions:
349            return rename_func("MAX")(self, expression)
350
351        return self.sql(expression, "this")
352
353    def transaction_sql(self, expression: exp.Transaction) -> str:
354        this = expression.this
355        this = f" {this}" if this else ""
356        return f"BEGIN{this} TRANSACTION"
357
358    def isascii_sql(self, expression: exp.IsAscii) -> str:
359        return f"(NOT {self.sql(expression.this)} GLOB CAST(x'2a5b5e012d7f5d2a' AS TEXT))"
360
361    @unsupported_args("this")
362    def currentschema_sql(self, expression: exp.CurrentSchema) -> str:
363        return "'main'"
364
365    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
366        self.unsupported("SQLite does not support IGNORE NULLS.")
367        return self.sql(expression.this)
368
369    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
370        return self.sql(expression.this)
371
372    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
373        if (
374            expression.text("kind").upper() == "RANGE"
375            and expression.text("start").upper() == "CURRENT ROW"
376        ):
377            return "RANGE CURRENT ROW"
378
379        return super().windowspec_sql(expression)

Generator converts a given syntax tree to the corresponding SQL string.

Arguments:
  • pretty: Whether to format the produced SQL string. Default: False.
  • identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True: Always quote except for specials cases. 'safe': Only quote identifiers that are case insensitive.
  • normalize: Whether to normalize identifiers to lowercase. Default: False.
  • pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
  • indent: The indentation size in a formatted string. For example, this affects the indentation of subqueries and filters under a WHERE clause. Default: 2.
  • normalize_functions: How to normalize function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
  • unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
  • max_unsupported: 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: Whether the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. 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 to preserve comments in the output SQL code. Default: True
SELECT_KINDS: tuple[str, ...] = ()
TRY_SUPPORTED = False
SUPPORTS_UESCAPE = False
SUPPORTS_DECODE_CASE = False
AFTER_HAVING_MODIFIER_TRANSFORMS = {'windows': <function <lambda>>, 'qualify': <function <lambda>>}
JOIN_HINTS = False
TABLE_HINTS = False
QUERY_HINTS = False
NVL2_SUPPORTED = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = False
SUPPORTS_CREATE_TABLE_LIKE = False
SUPPORTS_TABLE_ALIAS_COLUMNS = False
SUPPORTS_TO_NUMBER = False
SUPPORTS_WINDOW_EXCLUDE = True
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
SUPPORTS_MEDIAN = False
JSON_KEY_VALUE_PAIR_SEP = ','
PARSE_JSON_NAME: str | None = None
TYPE_MAPPING = {<DType.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <DType.NCHAR: 'NCHAR'>: 'TEXT', <DType.NVARCHAR: 'NVARCHAR'>: 'TEXT', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <DType.LONGTEXT: 'LONGTEXT'>: 'TEXT', <DType.TINYTEXT: 'TINYTEXT'>: 'TEXT', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <DType.LONGBLOB: 'LONGBLOB'>: 'BLOB', <DType.TINYBLOB: 'TINYBLOB'>: 'BLOB', <DType.INET: 'INET'>: 'INET', <DType.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP', <DType.BOOLEAN: 'BOOLEAN'>: 'INTEGER', <DType.TINYINT: 'TINYINT'>: 'INTEGER', <DType.SMALLINT: 'SMALLINT'>: 'INTEGER', <DType.INT: 'INT'>: 'INTEGER', <DType.BIGINT: 'BIGINT'>: 'INTEGER', <DType.FLOAT: 'FLOAT'>: 'REAL', <DType.DOUBLE: 'DOUBLE'>: 'REAL', <DType.DECIMAL: 'DECIMAL'>: 'REAL', <DType.CHAR: 'CHAR'>: 'TEXT', <DType.VARCHAR: 'VARCHAR'>: 'TEXT', <DType.BINARY: 'BINARY'>: 'BLOB', <DType.VARBINARY: 'VARBINARY'>: 'BLOB'}
TOKEN_MAPPING = {<TokenType.AUTO_INCREMENT: 228>: 'AUTOINCREMENT'}
TRANSFORMS = {<class 'sqlglot.expressions.query.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.core.Adjacent'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainedBy'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.AssumeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentCatalog'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.SessionUser'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApiProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.EndStatement'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HybridProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.datatypes.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAnyTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAllTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBPathExists'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function SQLiteGenerator.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.NetFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsLeft'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsRight'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.PositionalColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InvisibleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ZeroFillColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.SafeFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.TriggerExecute'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcDate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTime'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTimestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Variadic'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ForceProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.aggregate.AnyValue'>: <function any_value_to_max_sql>, <class 'sqlglot.expressions.string.Chr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Concat'>: <function concat_to_dpipe_sql>, <class 'sqlglot.expressions.aggregate.CountIf'>: <function count_if_to_sum>, <class 'sqlglot.expressions.ddl.Create'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.temporal.CurrentDate'>: <function SQLiteGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.CurrentTime'>: <function SQLiteGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.CurrentTimestamp'>: <function SQLiteGenerator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentVersion'>: <function SQLiteGenerator.<lambda>>, <class 'sqlglot.expressions.query.ColumnDef'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function SQLiteGenerator.<lambda>>, <class 'sqlglot.expressions.functions.If'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.ILike'>: <function no_ilike_sql>, <class 'sqlglot.expressions.json.JSONArrayAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Levenshtein'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalOr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalAnd'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.Pivot'>: <function no_pivot_sql>, <class 'sqlglot.expressions.functions.Rand'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.StrPosition'>: <function SQLiteGenerator.<lambda>>, <class 'sqlglot.expressions.query.TableSample'>: <function no_tablesample_sql>, <class 'sqlglot.expressions.temporal.TimeStrToTime'>: <function SQLiteGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimeToStr'>: <function SQLiteGenerator.<lambda>>, <class 'sqlglot.expressions.functions.TryCast'>: <function no_trycast_sql>, <class 'sqlglot.expressions.temporal.TsOrDsToTimestamp'>: <function SQLiteGenerator.<lambda>>}
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.AlgorithmProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ApiProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.AutoIncrementProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.BackupProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.BlockCompressionProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ChecksumProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.CollateProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.query.Cluster'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ClusteredByProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ClusterProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DistributedByProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DuplicateKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DataBlocksizeProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DataDeletionProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DefinerProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DictRange'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DictProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DistKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EncodeProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EngineProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.FallbackProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.FreespaceProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.HeapProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.HybridProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.IncludeProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.IsolatedLoadingProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.JournalProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.LikeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LocationProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.LockProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.LockingProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.LogProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.MergeBlockRatioProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ModuleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.OnProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.query.Order'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.PartitionedOfProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.constraints.PrimaryKey'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.Property'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RefreshTriggerProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RollupProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowFormatProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowFormatDelimitedProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowFormatSerdeProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SampleProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SchemaCommentProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SecureProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SerdeProperties'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.ddl.Set'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SetProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SharingProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.ddl.SequenceProperties'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.ddl.TriggerProperties'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SortKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StorageHandlerProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StrictProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.Tags'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TransientProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.ddl.MergeTreeTTL'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.UsingProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithDataProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithSystemVersioningProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ForceProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>}
LIMIT_FETCH = 'LIMIT'
def insert_sql(self, expression: sqlglot.expressions.dml.Insert) -> str:
210    def insert_sql(self, expression: exp.Insert) -> str:
211        if expression.args.get("ignore"):
212            expression.set("ignore", False)
213            expression.set("alternative", "IGNORE")
214
215        return super().insert_sql(expression)
def bitwiseandagg_sql(self, expression: sqlglot.expressions.math.BitwiseAndAgg) -> str:
217    def bitwiseandagg_sql(self, expression: exp.BitwiseAndAgg) -> str:
218        self.unsupported("BITWISE_AND aggregation is not supported in SQLite")
219        return self.function_fallback_sql(expression)
def bitwiseoragg_sql(self, expression: sqlglot.expressions.math.BitwiseOrAgg) -> str:
221    def bitwiseoragg_sql(self, expression: exp.BitwiseOrAgg) -> str:
222        self.unsupported("BITWISE_OR aggregation is not supported in SQLite")
223        return self.function_fallback_sql(expression)
def bitwisexoragg_sql(self, expression: sqlglot.expressions.math.BitwiseXorAgg) -> str:
225    def bitwisexoragg_sql(self, expression: exp.BitwiseXorAgg) -> str:
226        self.unsupported("BITWISE_XOR aggregation is not supported in SQLite")
227        return self.function_fallback_sql(expression)
def jsonextract_sql(self, expression: sqlglot.expressions.json.JSONExtract) -> str:
229    def jsonextract_sql(self, expression: exp.JSONExtract) -> str:
230        if expression.expressions:
231            return self.function_fallback_sql(expression)
232        return arrow_json_extract_sql(self, expression)
def jsonextractscalar_sql(self, expression: sqlglot.expressions.json.JSONExtractScalar) -> str:
234    def jsonextractscalar_sql(self, expression: exp.JSONExtractScalar) -> str:
235        if expression.args.get("json_subtype"):
236            # json_extract() keeps the JSON subtype on object/array results;
237            # ->> strips it, observable when the result feeds another JSON function
238            return self.func("JSON_EXTRACT", expression.this, expression.expression)
239        return arrow_json_extract_sql(self, expression)
def dateadd_sql(self, expression: sqlglot.expressions.temporal.DateAdd) -> str:
241    def dateadd_sql(self, expression: exp.DateAdd) -> str:
242        modifier = expression.expression
243        unit = expression.args.get("unit")
244        # An INTERVAL amount carries its own unit, e.g. DATE_ADD(d, INTERVAL 1 DAY);
245        # unwrap it so the unit is not left inside the quoted modifier string.
246        if isinstance(modifier, exp.Interval):
247            unit = unit or modifier.unit
248            modifier = modifier.this
249        modifier = modifier.name if modifier.is_string else self.sql(modifier)
250        modifier = f"'{modifier} {unit.name}'" if unit else f"'{modifier}'"
251        return self.func("DATE", expression.this, modifier)
def cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
253    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
254        if expression.is_type("date"):
255            return self.func("DATE", expression.this)
256
257        return super().cast_sql(expression)
def computedcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.ComputedColumnConstraint) -> str:
262    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
263        if expression.args.get("data_type"):
264            self.unsupported("SQLite generated columns do not support a data type")
265
266        this = expression.this
267        this_sql = self.sql(this) if isinstance(this, exp.Paren) else f"({self.sql(this)})"
268        storage = " STORED" if expression.args.get("persisted") else ""
269        not_null = " NOT NULL" if expression.args.get("not_null") else ""
270        return f"AS {this_sql}{storage}{not_null}"
@unsupported_args('decimals')
def trunc_sql(self, expression: sqlglot.expressions.math.Trunc) -> str:
276    @unsupported_args("decimals")
277    def trunc_sql(self, expression: exp.Trunc) -> str:
278        return self.func("TRUNC", expression.this)
def generateseries_sql(self, expression: sqlglot.expressions.array.GenerateSeries) -> str:
280    def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
281        parent = expression.parent
282        alias = parent and parent.args.get("alias")
283
284        if isinstance(alias, exp.TableAlias) and alias.columns:
285            column_alias = alias.columns[0]
286            alias.set("columns", None)
287            sql = self.sql(
288                exp.select(exp.alias_("value", column_alias)).from_(expression).subquery()
289            )
290        else:
291            sql = self.function_fallback_sql(expression)
292
293        return sql
def datediff_sql(self, expression: sqlglot.expressions.temporal.DateDiff) -> str:
295    def datediff_sql(self, expression: exp.DateDiff) -> str:
296        unit = expression.args.get("unit")
297        unit = unit.name.upper() if unit else "DAY"
298
299        sql = f"(JULIANDAY({self.sql(expression, 'this')}) - JULIANDAY({self.sql(expression, 'expression')}))"
300
301        if unit == "MONTH":
302            sql = f"{sql} / 30.0"
303        elif unit == "YEAR":
304            sql = f"{sql} / 365.0"
305        elif unit == "HOUR":
306            sql = f"{sql} * 24.0"
307        elif unit == "MINUTE":
308            sql = f"{sql} * 1440.0"
309        elif unit == "SECOND":
310            sql = f"{sql} * 86400.0"
311        elif unit == "MILLISECOND":
312            sql = f"{sql} * 86400000.0"
313        elif unit == "MICROSECOND":
314            sql = f"{sql} * 86400000000.0"
315        elif unit == "NANOSECOND":
316            sql = f"{sql} * 8640000000000.0"
317        else:
318            self.unsupported(f"DATEDIFF unsupported for '{unit}'.")
319
320        return f"CAST({sql} AS INTEGER)"
def groupconcat_sql(self, expression: sqlglot.expressions.aggregate.GroupConcat) -> str:
323    def groupconcat_sql(self, expression: exp.GroupConcat) -> str:
324        this = expression.this
325        distinct = find_in_scope(expression, exp.Distinct)
326
327        if distinct:
328            this = distinct.expressions[0]
329            distinct_sql = "DISTINCT "
330        else:
331            distinct_sql = ""
332
333        if isinstance(expression.this, exp.Order):
334            self.unsupported("SQLite GROUP_CONCAT doesn't support ORDER BY.")
335            if expression.this.this and not distinct:
336                this = expression.this.this
337
338        separator = expression.args.get("separator")
339        return f"GROUP_CONCAT({distinct_sql}{self.format_args(this, separator)})"
def least_sql(self, expression: sqlglot.expressions.functions.Least) -> str:
341    def least_sql(self, expression: exp.Least) -> str:
342        if expression.expressions:
343            return rename_func("MIN")(self, expression)
344
345        return self.sql(expression, "this")
def greatest_sql(self, expression: sqlglot.expressions.functions.Greatest) -> str:
347    def greatest_sql(self, expression: exp.Greatest) -> str:
348        if expression.expressions:
349            return rename_func("MAX")(self, expression)
350
351        return self.sql(expression, "this")
def transaction_sql(self, expression: sqlglot.expressions.ddl.Transaction) -> str:
353    def transaction_sql(self, expression: exp.Transaction) -> str:
354        this = expression.this
355        this = f" {this}" if this else ""
356        return f"BEGIN{this} TRANSACTION"
def isascii_sql(self, expression: sqlglot.expressions.string.IsAscii) -> str:
358    def isascii_sql(self, expression: exp.IsAscii) -> str:
359        return f"(NOT {self.sql(expression.this)} GLOB CAST(x'2a5b5e012d7f5d2a' AS TEXT))"
@unsupported_args('this')
def currentschema_sql(self, expression: sqlglot.expressions.functions.CurrentSchema) -> str:
361    @unsupported_args("this")
362    def currentschema_sql(self, expression: exp.CurrentSchema) -> str:
363        return "'main'"
def ignorenulls_sql(self, expression: sqlglot.expressions.core.IgnoreNulls) -> str:
365    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
366        self.unsupported("SQLite does not support IGNORE NULLS.")
367        return self.sql(expression.this)
def respectnulls_sql(self, expression: sqlglot.expressions.core.RespectNulls) -> str:
369    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
370        return self.sql(expression.this)
def windowspec_sql(self, expression: sqlglot.expressions.query.WindowSpec) -> str:
372    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
373        if (
374            expression.text("kind").upper() == "RANGE"
375            and expression.text("start").upper() == "CURRENT ROW"
376        ):
377            return "RANGE CURRENT ROW"
378
379        return super().windowspec_sql(expression)
Inherited Members
sqlglot.generator.Generator
Generator
NULL_ORDERING_SUPPORTED
WINDOW_FUNCS_WITH_NULL_ORDERING
IGNORE_NULLS_IN_FUNC
IGNORE_NULLS_BEFORE_ORDER
LOCKING_READS_SUPPORTED
WRAP_DERIVED_VALUES
CREATE_FUNCTION_RETURN_AS
MATCHED_BY_SOURCE
SUPPORTS_MERGE_WHERE
SINGLE_STRING_INTERVAL
INTERVAL_ALLOWS_PLURAL_FORM
AUTO_REFRESH_BARE_INTERVALS
LIMIT_ONLY_LITERALS
RENAME_TABLE_WITH_DB
GROUPINGS_SEP
INDEX_ON
INOUT_SEPARATOR
DIRECTED_JOINS
QUERY_HINT_SEP
IS_BOOL_ALLOWED
DUPLICATE_KEY_UPDATE_WITH_SET
LIMIT_IS_TOP
RETURNING_END
EXTRACT_ALLOWS_QUOTES
TZ_TO_WITH_TIME_ZONE
VALUES_AS_TABLE
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
UNNEST_WITH_ORDINALITY
SEMI_ANTI_JOIN_WITH_SIDE
COMPUTED_COLUMN_WITH_TYPE
SUPPORTS_TABLE_COPY
TABLESAMPLE_REQUIRES_PARENS
TABLESAMPLE_SIZE_IS_ROWS
TABLESAMPLE_KEYWORDS
TABLESAMPLE_WITH_METHOD
TABLESAMPLE_SEED_KEYWORD
HISTORICAL_DATA_POST_ALIAS
COLLATE_IS_FUNC
DATA_TYPE_SPECIFIERS_ALLOWED
ENSURE_BOOLS
CTE_RECURSIVE_KEYWORD_REQUIRED
SUPPORTS_SINGLE_ARG_CONCAT
LAST_DAY_SUPPORTS_DATE_PART
SUPPORTS_NAMED_CTE_COLUMNS
UNPIVOT_ALIASES_ARE_IDENTIFIERS
PIVOT_ALIAS_WITH_AS
INSERT_OVERWRITE
SUPPORTS_SELECT_INTO
SUPPORTS_UNLOGGED_TABLES
SUPPORTS_MODIFY_COLUMN
SUPPORTS_CHANGE_COLUMN
SUPPORTS_ALTER_COLUMN_NULLABILITY
SUPPORTS_ALTER_COLUMN_IF_EXISTS
LIKE_PROPERTY_INSIDE_SCHEMA
MULTI_ARG_DISTINCT
JSON_TYPE_REQUIRED_FOR_EXTRACTION
JSON_PATH_SINGLE_QUOTE_ESCAPE
JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
CAN_IMPLEMENT_ARRAY_ANY
SET_OP_MODIFIERS
COPY_PARAMS_ARE_WRAPPED
COPY_PARAMS_EQ_REQUIRED
COPY_HAS_INTO_KEYWORD
UNICODE_SUBSTITUTE
STAR_EXCEPT
HEX_FUNC
WITH_PROPERTIES_PREFIX
QUOTE_JSON_PATH
PAD_FILL_PATTERN_IS_REQUIRED
SUPPORTS_EXPLODING_PROJECTIONS
ARRAY_CONCAT_IS_VAR_LEN
SUPPORTS_CONVERT_TIMEZONE
SUPPORTS_UNIX_SECONDS
ALTER_SET_WRAPPED
NORMALIZE_EXTRACT_DATE_PARTS
ARRAY_SIZE_NAME
ALTER_SET_TYPE
ARRAY_SIZE_DIM_REQUIRED
SUPPORTS_BETWEEN_FLAGS
SUPPORTS_LIKE_QUANTIFIERS
MATCH_AGAINST_TABLE_PREFIX
SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD
DECLARE_DEFAULT_ASSIGNMENT
UPDATE_STATEMENT_SUPPORTS_FROM
STAR_EXCLUDE_REQUIRES_DERIVED_TABLE
SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY
UNSUPPORTED_TYPES
TYPE_PARAM_SETTINGS
TIME_PART_SINGULARS
STRUCT_DELIMITER
PARAMETER_TOKEN
NAMED_PLACEHOLDER_TOKEN
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
RESERVED_KEYWORDS
WITH_SEPARATED_COMMENTS
EXCLUDE_COMMENTS
UNWRAPPED_INTERVAL_VALUES
PARAMETERIZABLE_TEXT_TYPES
EXPRESSIONS_WITHOUT_NESTED_CTES
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS
SAFE_JSON_PATH_KEY_RE
SENTINEL_LINE_BREAK
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages
generate
preprocess
unsupported
sep
seg
sanitize_comment
maybe_comment
wrap
no_identify
normalize_func
indent
sql
uncache_sql
cache_sql
characterset_sql
column_parts
column_sql
pseudocolumn_sql
columnposition_sql
columndef_sql
columnconstraint_sql
autoincrementcolumnconstraint_sql
compresscolumnconstraint_sql
generatedasidentitycolumnconstraint_sql
generatedasrowcolumnconstraint_sql
periodforsystemtimeconstraint_sql
notnullcolumnconstraint_sql
primarykeycolumnconstraint_sql
uniquecolumnconstraint_sql
inoutcolumnconstraint_sql
createable_sql
create_sql
sequenceproperties_sql
triggerproperties_sql
triggerreferencing_sql
triggerevent_sql
clone_sql
describe_sql
heredoc_sql
prepend_ctes
with_sql
cte_sql
tablealias_sql
bitstring_sql
hexstring_sql
bytestring_sql
unicodestring_sql
rawstring_sql
datatypeparam_sql
datatype_param_bound_limiter
datatype_sql
directory_sql
delete_sql
drop_sql
set_operation
set_operations
fetch_sql
limitoptions_sql
filter_sql
hint_sql
indexparameters_sql
index_sql
dynamicidentifier_sql
identifier_sql
hex_sql
lowerhex_sql
inputoutputformat_sql
national_sql
partition_sql
properties_sql
root_properties
properties
with_properties
locate_properties
property_name
property_sql
uuidproperty_sql
likeproperty_sql
fallbackproperty_sql
journalproperty_sql
freespaceproperty_sql
checksumproperty_sql
mergeblockratioproperty_sql
moduleproperty_sql
datablocksizeproperty_sql
blockcompressionproperty_sql
isolatedloadingproperty_sql
partitionboundspec_sql
partitionedofproperty_sql
lockingproperty_sql
withdataproperty_sql
withsystemversioningproperty_sql
introducer_sql
kill_sql
pseudotype_sql
objectidentifier_sql
onconflict_sql
returning_sql
rowformatdelimitedproperty_sql
withtablehint_sql
indextablehint_sql
historicaldata_sql
table_parts
table_sql
tablefromrows_sql
tablesample_sql
pivot_sql
version_sql
tuple_sql
update_sql
values_sql
var_sql
into_sql
from_sql
groupingsets_sql
rollup_sql
rollupindex_sql
rollupproperty_sql
cube_sql
group_sql
having_sql
connect_sql
prior_sql
join_sql
lambda_sql
lateral_op
lateral_sql
limit_sql
offset_sql
setitem_sql
set_sql
queryband_sql
pragma_sql
lock_sql
literal_sql
escape_str
loaddata_sql
null_sql
boolean_sql
booland_sql
boolor_sql
order_sql
withfill_sql
cluster_sql
clusterproperty_sql
distribute_sql
sort_sql
ordered_sql
matchrecognizemeasure_sql
matchrecognize_sql
query_modifiers
options_modifier
forclause_sql
queryoption_sql
offset_limit_modifiers
after_limit_modifiers
select_sql
schema_sql
schema_columns_sql
star_sql
parameter_sql
sessionparameter_sql
placeholder_sql
subquery_sql
qualify_sql
unnest_sql
prewhere_sql
where_sql
window_sql
partition_by_sql
withingroup_sql
between_sql
bracket_offset_expressions
bracket_sql
all_sql
any_sql
exists_sql
case_sql
constraint_sql
nextvaluefor_sql
extract_sql
trim_sql
convert_concat_args
concat_sql
concatws_sql
check_sql
foreignkey_sql
primarykey_sql
timeserieskey_sql
if_sql
matchagainst_sql
jsonkeyvalue_sql
jsonpath_sql
json_path_part
formatjson_sql
formatphrase_sql
jsonarray_sql
jsonarrayagg_sql
jsoncolumndef_sql
jsonschema_sql
jsontable_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
pivotalias_sql
aliases_sql
atindex_sql
attimezone_sql
fromtimezone_sql
fromiso8601date_sql
fromiso8601timestamp_sql
fromiso8601timestampnanos_sql
add_sql
and_sql
or_sql
xor_sql
connector_sql
bitwiseand_sql
bitwiseleftshift_sql
bitwisenot_sql
bitwiseor_sql
bitwiserightshift_sql
bitwisexor_sql
strtotime_sql
strtodate_sql
parsedatetime_sql
currentdate_sql
collate_sql
command_sql
comment_sql
mergetreettlaction_sql
mergetreettl_sql
commit_sql
rollback_sql
altercolumn_sql
modifycolumn_sql
alterindex_sql
alterdiststyle_sql
altersortkey_sql
alterrename_sql
renamecolumn_sql
alterset_sql
alter_sql
altersession_sql
add_column_sql
droppartition_sql
dropprimarykey_sql
addconstraint_sql
addpartition_sql
distinct_sql
havingmax_sql
intdiv_sql
dpipe_sql
div_sql
safedivide_sql
overlaps_sql
distance_sql
distancend_sql
dot_sql
eq_sql
propertyeq_sql
escape_sql
glob_sql
gt_sql
gte_sql
is_sql
like_sql
ilike_sql
match_sql
similarto_sql
lt_sql
lte_sql
mod_sql
mul_sql
neq_sql
nullsafeeq_sql
nullsafeneq_sql
sub_sql
trycast_sql
jsoncast_sql
try_sql
log_sql
use_sql
binary
ceil_floor
function_fallback_sql
func
format_args
too_wide
format_time
expressions
op_expressions
naked_property
tag_sql
token_sql
userdefinedfunction_sql
macrooverloads_sql
macrooverload_sql
joinhint_sql
kwarg_sql
when_sql
whens_sql
merge_sql
tochar_sql
tonumber_sql
dictproperty_sql
dictrange_sql
dictsubproperty_sql
duplicatekeyproperty_sql
uniquekeyproperty_sql
distributedbyproperty_sql
oncluster_sql
clusteredbyproperty_sql
anyvalue_sql
querytransform_sql
indexconstraintoption_sql
checkcolumnconstraint_sql
indexcolumnconstraint_sql
nvl2_sql
comprehension_sql
columnprefix_sql
opclass_sql
predict_sql
generateembedding_sql
generatetext_sql
generatetable_sql
generatebool_sql
generateint_sql
generatedouble_sql
mltranslate_sql
mlforecast_sql
aiforecast_sql
featuresattime_sql
vectorsearch_sql
forin_sql
refresh_sql
toarray_sql
tsordstotime_sql
tsordstotimestamp_sql
tsordstodatetime_sql
tsordstodate_sql
unixdate_sql
lastday_sql
arrayany_sql
struct_sql
partitionrange_sql
truncatetable_sql
convert_sql
copyparameter_sql
credentials_sql
copy_sql
semicolon_sql
datadeletionproperty_sql
maskingpolicycolumnconstraint_sql
gapfill_sql
scope_resolution
scoperesolution_sql
parsejson_sql
rand_sql
changes_sql
pad_sql
summarize_sql
explodinggenerateseries_sql
converttimezone_sql
json_sql
jsonvalue_sql
skipjsoncolumn_sql
conditionalinsert_sql
multitableinserts_sql
oncondition_sql
jsonextractquote_sql
jsonexists_sql
arrayagg_sql
slice_sql
apply_sql
grant_sql
revoke_sql
grantprivilege_sql
grantprincipal_sql
columns_sql
overlay_sql
todouble_sql
string_sql
median_sql
overflowtruncatebehavior_sql
unixseconds_sql
arraysize_sql
attach_sql
detach_sql
attachoption_sql
watermarkcolumnconstraint_sql
encodeproperty_sql
includeproperty_sql
xmlelement_sql
xmlkeyvalueoption_sql
partitionbyrangeproperty_sql
partitionbyrangepropertydynamic_sql
unpivotcolumns_sql
analyzesample_sql
analyzestatistics_sql
analyzehistogram_sql
analyzedelete_sql
analyzelistchainedrows_sql
analyzevalidate_sql
analyze_sql
xmltable_sql
xmlnamespace_sql
export_sql
declare_sql
declareitem_sql
recursivewithsearch_sql
parameterizedagg_sql
anonymousaggfunc_sql
combinedaggfunc_sql
combinedparameterizedagg_sql
show_sql
install_sql
get_put_sql
translatecharacters_sql
decodecase_sql
semanticview_sql
getextract_sql
datefromunixdate_sql
space_sql
buildproperty_sql
refreshtriggerproperty_sql
modelattribute_sql
directorystage_sql
uuid_sql
initcap_sql
localtime_sql
localtimestamp_sql
weekstart_name
weekstart_sql
chr_sql
block_sql
functionspecification_sql
storedprocedure_sql
ifblock_sql
casestatement_sql
whileblock_sql
loopblock_sql
repeatblock_sql
leave_sql
iterate_sql
execute_sql
executesql_sql
altermodifysqlsecurity_sql
usingproperty_sql
renameindex_sql