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 count_if_to_sum, 10 generate_series_sql, 11 groupconcat_sql, 12 no_ilike_sql, 13 no_pivot_sql, 14 no_tablesample_sql, 15 no_trycast_sql, 16 rename_func, 17 strposition_sql, 18) 19from sqlglot.generator import unsupported_args 20from sqlglot.optimizer.helpers import projection_has_aggregate 21from sqlglot.parsers.sqlite import SQLITE_NOW 22from sqlglot.tokens import TokenType 23 24DATETIME_TYPES = ( 25 exp.DType.DATETIME, 26 exp.DType.TIMESTAMP, 27 exp.DType.TIMESTAMPNTZ, 28 exp.DType.TIMESTAMPTZ, 29 exp.DType.TIMESTAMPLTZ, 30) 31DATE_PART_FORMATS = { 32 "YEAR": "%Y", 33 "MONTH": "%m", 34 "DAY": "%d", 35 "DOY": "%j", 36 "DAYOFYEAR": "%j", 37 "QUARTER": "%m", 38} 39 40 41def _transform_create(expression: exp.Expr) -> exp.Expr: 42 """Move primary key to a column and place auto_increment after it.""" 43 schema = expression.this 44 45 if isinstance(expression, exp.Create) and isinstance(schema, exp.Schema): 46 defs = {} 47 primary_key = None 48 49 for e in schema.expressions: 50 if isinstance(e, exp.ColumnDef): 51 defs[e.name] = e 52 elif isinstance(e, exp.PrimaryKey): 53 primary_key = e 54 55 if primary_key and len(primary_key.expressions) == 1: 56 column = defs[primary_key.expressions[0].name] 57 column.append( 58 "constraints", exp.ColumnConstraint(kind=exp.PrimaryKeyColumnConstraint()) 59 ) 60 schema.expressions.remove(primary_key) 61 62 for column in defs.values(): 63 primary_key_index = -1 64 auto_increment = None 65 auto_increment_index = -1 66 67 for i, constraint in enumerate(column.constraints): 68 if isinstance(constraint.kind, exp.PrimaryKeyColumnConstraint): 69 primary_key_index = i 70 elif isinstance(constraint.kind, exp.AutoIncrementColumnConstraint): 71 auto_increment = constraint 72 auto_increment_index = i 73 74 if auto_increment is not None and 0 <= auto_increment_index < primary_key_index: 75 column.constraints.remove(auto_increment) 76 column.constraints.insert(primary_key_index, auto_increment) 77 78 return expression 79 80 81def _generated_to_auto_increment(expression: exp.Expr) -> exp.Expr: 82 if not isinstance(expression, exp.ColumnDef): 83 return expression 84 85 generated = expression.find(exp.GeneratedAsIdentityColumnConstraint) 86 87 # Only rewrite true identity columns. Expression-bearing forms are computed 88 # columns (GENERATED ALWAYS AS (expr)) and must keep their expression. 89 if generated and generated.expression is None: 90 t.cast(exp.ColumnConstraint, generated.parent).pop() 91 92 not_null = expression.find(exp.NotNullColumnConstraint) 93 if not_null: 94 t.cast(exp.ColumnConstraint, not_null.parent).pop() 95 96 expression.append( 97 "constraints", exp.ColumnConstraint(kind=exp.AutoIncrementColumnConstraint()) 98 ) 99 100 return expression 101 102 103def _date_delta_operands(expression: exp.Expr) -> tuple[exp.Expr, exp.Expr] | None: 104 if isinstance(expression, (exp.DateAdd, exp.DateSub)): 105 return expression.this, expression.expression 106 if isinstance(expression, (exp.Add, exp.Sub)): 107 base, interval = expression.left, expression.right 108 if ( 109 isinstance(expression, exp.Add) 110 and isinstance(base, exp.Interval) 111 and not isinstance(interval, exp.Interval) 112 ): 113 base, interval = interval, base 114 if isinstance(interval, exp.Interval) and interval.unit: 115 return base, interval 116 return None 117 118 119def _uncast_timestamp(expression: exp.Expr) -> exp.Expr: 120 expression = expression.unnest() 121 while isinstance(expression, exp.Cast) and expression.is_type(*DATETIME_TYPES): 122 if expression.to.expressions: 123 precision = expression.to.expressions[0].this 124 # SQLite date functions preserve milliseconds. A coarser cast can change the comparison. 125 if ( 126 not isinstance(precision, exp.Literal) 127 or not precision.is_int 128 or int(precision.to_py()) < 3 129 ): 130 break 131 expression = expression.this.unnest() 132 return expression 133 134 135def _comparison_sql(op: str) -> t.Callable[[SQLiteGenerator, exp.Binary], str]: 136 def _sql(self: SQLiteGenerator, expression: exp.Binary) -> str: 137 self._coerce_date_comparison(expression.left, expression.right) 138 return self.binary(expression, op) 139 140 return _sql 141 142 143def _is_sqlite_aggregate(func: exp.AggFunc) -> bool: 144 # SQLite's MIN and MAX are scalar when called with multiple arguments. 145 return not isinstance(func, (exp.Min, exp.Max)) or ( 146 not func.expressions and func.args.get("count") is None 147 ) 148 149 150def _has_aggregate_projection(select: exp.Select) -> bool: 151 # SQLite requires a projected aggregate outside any window to allow ungrouped HAVING. 152 if select.args.get("having"): 153 return any( 154 isinstance(node, exp.AggFunc) and _is_sqlite_aggregate(node) 155 for projection in select.selects 156 for node in projection.walk(prune=lambda n: isinstance(n, (exp.Query, exp.Window))) 157 ) 158 159 return any( 160 projection_has_aggregate( 161 p, select.args.get("windows"), aggregate_filter=_is_sqlite_aggregate 162 ) 163 for p in select.selects 164 ) 165 166 167class SQLiteGenerator(generator.Generator): 168 SELECT_KINDS = () 169 TRY_SUPPORTED = False 170 SUPPORTS_UESCAPE = False 171 SUPPORTS_DECODE_CASE = False 172 SET_OP_PARENTHESIZED_OPERANDS = False 173 174 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 175 176 JOIN_HINTS = False 177 TABLE_HINTS = False 178 QUERY_HINTS = False 179 NVL2_SUPPORTED = False 180 JSON_PATH_BRACKETED_KEY_SUPPORTED = False 181 SUPPORTS_CREATE_TABLE_LIKE = False 182 SUPPORTS_TABLE_ALIAS_COLUMNS = False 183 SUPPORTS_TO_NUMBER = False 184 SUPPORTS_WINDOW_EXCLUDE = True 185 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False 186 SUPPORTS_MEDIAN = False 187 JSON_KEY_VALUE_PAIR_SEP = "," 188 PARSE_JSON_NAME: str | None = None 189 190 SUPPORTED_JSON_PATH_PARTS = { 191 exp.JSONPathKey, 192 exp.JSONPathRoot, 193 exp.JSONPathSubscript, 194 } 195 196 TYPE_MAPPING = { 197 **{k: v for k, v in generator.Generator.TYPE_MAPPING.items() if k != exp.DType.BLOB}, 198 exp.DType.BOOLEAN: "INTEGER", 199 exp.DType.TINYINT: "INTEGER", 200 exp.DType.SMALLINT: "INTEGER", 201 exp.DType.INT: "INTEGER", 202 exp.DType.BIGINT: "INTEGER", 203 exp.DType.FLOAT: "REAL", 204 exp.DType.DOUBLE: "REAL", 205 exp.DType.DECIMAL: "REAL", 206 exp.DType.CHAR: "TEXT", 207 exp.DType.NCHAR: "TEXT", 208 exp.DType.VARCHAR: "TEXT", 209 exp.DType.NVARCHAR: "TEXT", 210 exp.DType.BINARY: "BLOB", 211 exp.DType.VARBINARY: "BLOB", 212 } 213 214 TOKEN_MAPPING = { 215 TokenType.AUTO_INCREMENT: "AUTOINCREMENT", 216 } 217 218 TRANSFORMS = { 219 **generator.Generator.TRANSFORMS, 220 exp.AnyValue: any_value_to_max_sql, 221 exp.Chr: rename_func("CHAR"), 222 exp.CountIf: count_if_to_sum, 223 exp.Create: transforms.preprocess([_transform_create]), 224 exp.CurrentDate: lambda *_: "CURRENT_DATE", 225 exp.CurrentTime: lambda *_: "CURRENT_TIME", 226 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 227 exp.CurrentVersion: lambda *_: "SQLITE_VERSION()", 228 exp.ColumnDef: transforms.preprocess([_generated_to_auto_increment]), 229 exp.DateStrToDate: lambda self, e: self.sql(e, "this"), 230 exp.EQ: _comparison_sql("="), 231 exp.GT: _comparison_sql(">"), 232 exp.GTE: _comparison_sql(">="), 233 exp.If: rename_func("IIF"), 234 exp.ILike: no_ilike_sql, 235 exp.JSONArrayAgg: unsupported_args("order", "null_handling", "return_type", "strict")( 236 rename_func("JSON_GROUP_ARRAY") 237 ), 238 exp.JSONObjectAgg: lambda self, e: self._jsonobject_sql(e, name="JSON_GROUP_OBJECT"), 239 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")( 240 rename_func("EDITDIST3") 241 ), 242 exp.LogicalOr: rename_func("MAX"), 243 exp.LogicalAnd: rename_func("MIN"), 244 exp.LT: _comparison_sql("<"), 245 exp.LTE: _comparison_sql("<="), 246 exp.NEQ: _comparison_sql("<>"), 247 exp.NullSafeEQ: _comparison_sql("IS"), 248 exp.NullSafeNEQ: _comparison_sql("IS NOT"), 249 exp.Pivot: no_pivot_sql, 250 exp.RegexpLike: lambda self, e: self.binary(e, "REGEXP"), 251 exp.Select: transforms.preprocess( 252 [ 253 transforms.eliminate_distinct_on, 254 transforms.eliminate_qualify, 255 transforms.eliminate_semi_and_anti_joins, 256 ] 257 ), 258 exp.StrPosition: lambda self, e: strposition_sql(self, e, func_name="INSTR"), 259 exp.TableSample: no_tablesample_sql, 260 exp.TimeStrToTime: lambda self, e: self.sql(e, "this"), 261 exp.TimeToStr: lambda self, e: self.func("STRFTIME", self.format_time(e), e.this), 262 exp.TryCast: no_trycast_sql, 263 exp.TsOrDsToTimestamp: lambda self, e: self.sql(e, "this"), 264 } 265 266 # SQLite doesn't generally support CREATE TABLE .. properties 267 # https://www.sqlite.org/lang_createtable.html 268 PROPERTIES_LOCATION = { 269 **{ 270 prop: exp.Properties.Location.UNSUPPORTED 271 for prop in generator.Generator.PROPERTIES_LOCATION 272 }, 273 # There are a few exceptions (e.g. temporary tables) which are supported or 274 # can be transpiled to SQLite, so we explicitly override them accordingly 275 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 276 exp.ModuleProperty: exp.Properties.Location.POST_SCHEMA, 277 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 278 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 279 exp.VirtualProperty: exp.Properties.Location.POST_CREATE, 280 exp.WithoutRowidProperty: exp.Properties.Location.POST_SCHEMA, 281 } 282 283 LIMIT_FETCH = "LIMIT" 284 285 def root_properties(self, properties: exp.Properties) -> str: 286 return self.expressions(properties, indent=False, sep=", ") 287 288 def group_sql(self, expression: exp.Group) -> str: 289 if any(isinstance(e, exp.Tuple) and not e.expressions for e in expression.expressions): 290 select = expression.parent 291 if ( 292 len(expression.expressions) == 1 293 and not any( 294 expression.args.get(k) for k in ("grouping_sets", "cube", "rollup", "totals") 295 ) 296 and isinstance(select, exp.Select) 297 and _has_aggregate_projection(select) 298 ): 299 return "" 300 301 self.unsupported("SQLite does not support GROUP BY ()") 302 303 return super().group_sql(expression) 304 305 def offset_limit_modifiers( 306 self, expression: exp.Expr, fetch: bool, limit: exp.Fetch | exp.Limit | None 307 ) -> list[str]: 308 if expression.args.get("offset") and ( 309 not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all) 310 ): 311 limit = exp.Limit(expression=exp.Literal.number(-1)) 312 return super().offset_limit_modifiers(expression, fetch, limit) 313 314 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 315 if any(expression.args.get(key) for key in ("order", "limit", "offset")): 316 query = expression.this 317 keys = ("order", "limit", "offset", "with_") 318 # Merge grouping modifiers unless doing so would overwrite an inner clause. 319 if any(expression.args.get(key) and query.args.get(key) for key in keys): 320 query = exp.select("*").from_(query.subquery(copy=False), copy=False) 321 for key in keys: 322 if value := expression.args.get(key): 323 query.set(key, value.pop()) 324 return self.sql(query) 325 326 return super().subquery_sql(expression, sep=sep) 327 328 def autoincrementcolumnconstraint_sql( 329 self, expression: exp.AutoIncrementColumnConstraint 330 ) -> str: 331 column = expression.find_ancestor(exp.ColumnDef) 332 if column and column.find(exp.PrimaryKeyColumnConstraint): 333 return super().autoincrementcolumnconstraint_sql(expression) 334 335 self.unsupported("SQLite AUTOINCREMENT requires an INTEGER PRIMARY KEY") 336 return "" 337 338 def insert_sql(self, expression: exp.Insert) -> str: 339 if expression.args.get("ignore"): 340 expression.set("ignore", False) 341 expression.set("alternative", "IGNORE") 342 343 return super().insert_sql(expression) 344 345 def rand_sql(self, expression: exp.Rand) -> str: 346 random = self.func("RANDOM", expression.this) 347 if any(expression.args.values()): 348 return random 349 350 # Keep 53 bits so even the largest draw is exactly representable and strictly below 1 after division. 351 return f"(CAST({random} & 9007199254740991 AS REAL) / 9007199254740992)" 352 353 def bitwiseandagg_sql(self, expression: exp.BitwiseAndAgg) -> str: 354 self.unsupported("BITWISE_AND aggregation is not supported in SQLite") 355 return self.function_fallback_sql(expression) 356 357 def bitwiseoragg_sql(self, expression: exp.BitwiseOrAgg) -> str: 358 self.unsupported("BITWISE_OR aggregation is not supported in SQLite") 359 return self.function_fallback_sql(expression) 360 361 def bitwisexoragg_sql(self, expression: exp.BitwiseXorAgg) -> str: 362 self.unsupported("BITWISE_XOR aggregation is not supported in SQLite") 363 return self.function_fallback_sql(expression) 364 365 def jsonextract_sql(self, expression: exp.JSONExtract) -> str: 366 if expression.expressions: 367 return self.function_fallback_sql(expression) 368 return arrow_json_extract_sql(self, expression) 369 370 def jsonextractscalar_sql(self, expression: exp.JSONExtractScalar) -> str: 371 if expression.args.get("json_subtype"): 372 # json_extract() keeps the JSON subtype on object/array results; 373 # ->> strips it, observable when the result feeds another JSON function 374 return self.func("JSON_EXTRACT", expression.this, expression.expression) 375 return arrow_json_extract_sql(self, expression) 376 377 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 378 if expression == SQLITE_NOW: 379 # SQLite date functions accept 'now' directly and retain its milliseconds. 380 if expression.arg_key == "this" and isinstance( 381 expression.parent, (exp.Date, exp.TimeToStr) 382 ): 383 return "'now'" 384 return self.func("STRFTIME", "'%Y-%m-%d %H:%M:%f'", "'now'") 385 return super().attimezone_sql(expression) 386 387 def extract_sql(self, expression: exp.Extract) -> str: 388 part = expression.name.upper() 389 fmt = DATE_PART_FORMATS.get(part) 390 value = expression.expression 391 # PostgreSQL DATE_PART returns double precision even for integral fields. 392 if fmt and value.unnest().is_type(exp.DType.DATE) and not expression.args.get("date_part"): 393 field: exp.Expr = exp.TimeToStr(this=value.copy(), format=exp.Literal.string(fmt)) 394 if part == "QUARTER": 395 # Adding 2 to the two-digit month coerces it to an integer before division. 396 quarter = (field + 2) / 3 397 quarter.set("typed", True) 398 field = quarter 399 # Default to REAL so division preserves fractions when EXTRACT is untyped. 400 dtype = ( 401 exp.DType.INT 402 if expression.is_type(*exp.DataType.INTEGER_TYPES) 403 else exp.DType.DOUBLE 404 ) 405 return self.sql(exp.cast(field, dtype, copy=False)) 406 407 return super().extract_sql(expression) 408 409 def dateadd_sql(self, expression: exp.DateAdd) -> str: 410 return self._date_delta_sql(expression, expression.this, expression.expression) 411 412 def _date_delta_sql(self, expression: exp.Expr, base: exp.Expr, modifier: exp.Expr) -> str: 413 unit_name, modifiers = self._date_modifiers(expression, modifier) 414 # DATE + INTERVAL can return DATE or TIMESTAMP depending on the source dialect. 415 if expression.is_type(exp.DType.DATE, exp.DType.DATE32): 416 func = "DATE" 417 elif expression.is_type(exp.DType.TIME, exp.DType.TIMETZ): 418 func = "TIME" 419 elif ( 420 expression.is_type(*exp.DataType.TEMPORAL_TYPES) 421 or unit_name in ("HOUR", "MINUTE", "SECOND") 422 or isinstance(base, exp.CurrentTimestamp) 423 or base.is_type(*DATETIME_TYPES) 424 ): 425 func = "DATETIME" 426 else: 427 if unit_name in ("DAY", "WEEK", "MONTH", "QUARTER", "YEAR") and ( 428 not base.type or base.is_type(exp.DType.UNKNOWN, *exp.DataType.TEXT_TYPES) 429 ): 430 self.unsupported( 431 "SQLite DATE() may discard the time in interval arithmetic. Cast text operands " 432 "to a temporal type, or qualify untyped columns and use annotate_types " 433 "with the source schema." 434 ) 435 func = "DATE" 436 437 return self.func(func, base, *modifiers) 438 439 def _date_modifiers( 440 self, expression: exp.Expr, modifier: exp.Expr 441 ) -> tuple[str, list[exp.Expr]]: 442 unit = expression.args.get("unit") 443 # An INTERVAL amount carries its own unit, e.g. DATE_ADD(d, INTERVAL 1 DAY); 444 # unwrap it so the unit is not left inside the quoted modifier string. 445 if isinstance(modifier, exp.Interval): 446 unit = unit or modifier.unit 447 modifier = modifier.this 448 449 if isinstance(expression, (exp.Sub, exp.DateSub)): 450 modifier = self._negate_date_modifier(modifier) 451 452 # Plural units (e.g. Postgres INTERVAL '2 hours') are valid SQLite modifiers 453 unit_name = unit.name.upper().removesuffix("S") if unit else "" 454 if unit_name == "WEEK": 455 modifier = modifier * 7 456 unit = exp.var("DAY") 457 elif unit_name == "QUARTER": 458 modifier = modifier * 3 459 unit = exp.var("MONTH") 460 461 modifier = modifier.unnest() 462 if ( 463 unit 464 and not isinstance(modifier, exp.Literal) 465 and not (isinstance(modifier, exp.Neg) and modifier.this.is_number) 466 ): 467 modifier = exp.DPipe( 468 this=exp.paren(modifier), 469 expression=exp.Literal.string(f" {unit.name}"), 470 ) 471 else: 472 value = modifier.name if modifier.is_string else self.sql(modifier) 473 modifier = exp.Literal.string(f"{value} {unit.name}" if unit else value) 474 modifiers: list[exp.Expr] = [modifier] 475 if unit_name in ("MONTH", "QUARTER", "YEAR"): 476 # SQLite otherwise rolls overflowing days into the following month. 477 if self.dialect.version >= (3, 46): 478 modifiers.append(exp.Literal.string("floor")) 479 else: 480 self.unsupported("Clamping month-end interval arithmetic requires SQLite 3.46+") 481 return unit_name, modifiers 482 483 def add_sql(self, expression: exp.Add) -> str: 484 operands = _date_delta_operands(expression) 485 if operands: 486 return self._date_delta_sql(expression, *operands) 487 return super().add_sql(expression) 488 489 def sub_sql(self, expression: exp.Sub) -> str: 490 operands = _date_delta_operands(expression) 491 if operands: 492 return self._date_delta_sql(expression, *operands) 493 return super().sub_sql(expression) 494 495 def datesub_sql(self, expression: exp.DateSub) -> str: 496 return self._date_delta_sql(expression, expression.this, expression.expression) 497 498 def _negate_date_modifier(self, amount: exp.Expr) -> exp.Expr: 499 amount = amount.unnest() 500 if isinstance(amount, exp.Neg): 501 return amount.this 502 if isinstance(amount, exp.Literal): 503 text = amount.name.removeprefix("+") 504 return exp.Literal.string(text[1:] if text.startswith("-") else f"-{text}") 505 return exp.Neg( 506 this=amount 507 if isinstance(amount, (exp.Column, exp.Func)) 508 else exp.paren(amount, copy=False) 509 ) 510 511 def _coerce_date_comparison(self, *operands: exp.Expr) -> None: 512 for operand in operands: 513 value = operand.unnest() 514 # Check for interval arithmetic before inspecting the operand or cast types. 515 candidate = value 516 while isinstance(candidate, exp.Cast): 517 candidate = candidate.this.unnest() 518 if ( 519 _date_delta_operands(candidate) 520 and value.is_type(*DATETIME_TYPES) 521 and _uncast_timestamp(value) is candidate 522 ): 523 break 524 else: 525 return 526 527 values = tuple(operand.unnest() for operand in operands) 528 if not any(value.is_type(exp.DType.DATE, exp.DType.DATE32) for value in values): 529 return 530 531 # Evaluate modifiers inside JULIANDAY. An intermediate DATETIME would drop fractional seconds. 532 for operand, value in zip(operands, values): 533 modifiers: list[exp.Expr] = [] 534 while value.is_type(*DATETIME_TYPES): 535 value = _uncast_timestamp(value) 536 delta = _date_delta_operands(value) 537 if not delta or value.is_type( 538 exp.DType.DATE, exp.DType.DATE32, exp.DType.TIME, exp.DType.TIMETZ 539 ): 540 break 541 base, amount = delta 542 _, inner_modifiers = self._date_modifiers(value, amount) 543 modifiers = inner_modifiers + modifiers 544 value = base.unnest() 545 operand.replace(exp.func("JULIANDAY", value, *modifiers)) 546 547 def between_sql(self, expression: exp.Between) -> str: 548 self._coerce_date_comparison( 549 expression.this, expression.args["low"], expression.args["high"] 550 ) 551 return super().between_sql(expression) 552 553 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 554 if expression.is_type("date"): 555 return self.func("DATE", expression.this) 556 if expression.is_type(*DATETIME_TYPES): 557 return self.func("DATETIME", expression.this) 558 if expression.is_type("time"): 559 return self.func("TIME", expression.this) 560 if expression.is_type("json", "jsonb"): 561 return self.func("JSON", expression.this) 562 563 return super().cast_sql(expression) 564 565 # https://www.sqlite.org/gencol.html 566 # Inline unsupported check: mypyc cannot compile @unsupported_args on an 567 # override of an undecorated base-class method. 568 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 569 if expression.args.get("data_type"): 570 self.unsupported("SQLite generated columns do not support a data type") 571 572 this = expression.this 573 this_sql = self.sql(this) if isinstance(this, exp.Paren) else f"({self.sql(this)})" 574 storage = " STORED" if expression.args.get("persisted") else "" 575 not_null = " NOT NULL" if expression.args.get("not_null") else "" 576 return f"AS {this_sql}{storage}{not_null}" 577 578 # Note: SQLite's TRUNC always returns REAL (e.g., trunc(10.99) -> 10.0), not INTEGER. 579 # This creates a transpilation gap affecting division semantics, similar to Presto. 580 # Unlike Presto where this only affects decimals=0, SQLite has no decimals parameter 581 # so every use of TRUNC is affected. Modeling precisely would require exp.FloatTrunc. 582 @unsupported_args("decimals") 583 def trunc_sql(self, expression: exp.Trunc) -> str: 584 return self.func("TRUNC", expression.this) 585 586 def generateseries_sql(self, expression: exp.GenerateSeries) -> str: 587 parent = expression.parent 588 alias = parent and parent.args.get("alias") 589 590 if isinstance(alias, exp.TableAlias) and alias.columns: 591 column_alias = alias.columns[0] 592 alias.set("columns", None) 593 sql = self.sql( 594 exp.select(exp.alias_("value", column_alias)).from_(expression).subquery() 595 ) 596 else: 597 sql = generate_series_sql("GENERATE_SERIES")(self, expression) 598 599 return sql 600 601 def datediff_sql(self, expression: exp.DateDiff) -> str: 602 unit = expression.args.get("unit") 603 unit = unit.name.upper() if unit else "DAY" 604 605 modifier = ( 606 exp.Literal.string("start of day") 607 if unit == "DAY" and expression.args.get("date_part_boundary") 608 else None 609 ) 610 end = self.func("JULIANDAY", expression.this, modifier) 611 start = self.func("JULIANDAY", expression.expression, modifier) 612 sql = f"({end} - {start})" 613 614 if unit == "MONTH": 615 sql = f"{sql} / 30.0" 616 elif unit == "YEAR": 617 sql = f"{sql} / 365.0" 618 elif unit == "HOUR": 619 sql = f"{sql} * 24.0" 620 elif unit == "MINUTE": 621 sql = f"{sql} * 1440.0" 622 elif unit == "SECOND": 623 sql = f"{sql} * 86400.0" 624 elif unit == "MILLISECOND": 625 sql = f"{sql} * 86400000.0" 626 elif unit == "MICROSECOND": 627 sql = f"{sql} * 86400000000.0" 628 elif unit == "NANOSECOND": 629 sql = f"{sql} * 86400000000000.0" 630 elif unit != "DAY": 631 self.unsupported(f"DATEDIFF unsupported for '{unit}'.") 632 633 return f"CAST({sql} AS INTEGER)" 634 635 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 636 node = expression.parent if isinstance(expression.parent, exp.Filter) else expression 637 window = node.parent 638 639 if ( 640 isinstance(expression.this, exp.Order) 641 and isinstance(window, exp.Window) 642 and window.this is node 643 ): 644 self.unsupported( 645 "SQLite GROUP_CONCAT window functions do not support argument ORDER BY" 646 ) 647 expression.set("this", expression.this.this) 648 649 this = expression.this 650 if isinstance(this, exp.Order): 651 this = this.this 652 if isinstance(this, exp.Distinct) and expression.args.get( 653 "separator" 654 ) == exp.Literal.string(","): 655 # DISTINCT aggregates accept one argument; SQLite already defaults to a comma separator. 656 expression.set("separator", None) 657 658 return groupconcat_sql( 659 self, expression, func_name="GROUP_CONCAT", sep=None, within_group=False 660 ) 661 662 def _greatest_least_sql(self, expression: exp.Greatest | exp.Least) -> str: 663 if not expression.expressions: 664 return self.sql(expression, "this") 665 666 name = "MAX" if isinstance(expression, exp.Greatest) else "MIN" 667 668 if not expression.args.get("ignore_nulls"): 669 return rename_func(name)(self, expression) 670 671 # SQLite's multi-argument MAX/MIN return NULL if any argument is NULL. 672 # GREATEST(a, b, c) -> MAX(COALESCE(a, b, c), COALESCE(b, c, a), COALESCE(c, a, b)). 673 args = [expression.this, *expression.expressions] 674 675 coalesces = [] 676 for i in range(len(args)): 677 rotated = args[i:] + args[:i] 678 coalesces.append(exp.Coalesce(this=rotated[0], expressions=rotated[1:])) 679 680 return self.func(name, *coalesces) 681 682 def greatest_sql(self, expression: exp.Greatest) -> str: 683 return self._greatest_least_sql(expression) 684 685 def least_sql(self, expression: exp.Least) -> str: 686 return self._greatest_least_sql(expression) 687 688 def transaction_sql(self, expression: exp.Transaction) -> str: 689 this = expression.this 690 this = f" {this}" if this else "" 691 return f"BEGIN{this} TRANSACTION" 692 693 def isascii_sql(self, expression: exp.IsAscii) -> str: 694 return f"(NOT {self.sql(expression.this)} GLOB CAST(x'2a5b5e012d7f5d2a' AS TEXT))" 695 696 @unsupported_args("this") 697 def currentschema_sql(self, expression: exp.CurrentSchema) -> str: 698 return "'main'" 699 700 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 701 self.unsupported("SQLite does not support IGNORE NULLS.") 702 return self.sql(expression.this) 703 704 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 705 return self.sql(expression.this) 706 707 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 708 if ( 709 expression.text("kind").upper() == "RANGE" 710 and expression.text("start").upper() == "CURRENT ROW" 711 and expression.args.get("end") is None 712 ): 713 return "RANGE CURRENT ROW" 714 715 return super().windowspec_sql(expression)
DATETIME_TYPES =
(<DType.DATETIME: 'DATETIME'>, <DType.TIMESTAMP: 'TIMESTAMP'>, <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <DType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>)
DATE_PART_FORMATS =
{'YEAR': '%Y', 'MONTH': '%m', 'DAY': '%d', 'DOY': '%j', 'DAYOFYEAR': '%j', 'QUARTER': '%m'}
168class SQLiteGenerator(generator.Generator): 169 SELECT_KINDS = () 170 TRY_SUPPORTED = False 171 SUPPORTS_UESCAPE = False 172 SUPPORTS_DECODE_CASE = False 173 SET_OP_PARENTHESIZED_OPERANDS = False 174 175 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 176 177 JOIN_HINTS = False 178 TABLE_HINTS = False 179 QUERY_HINTS = False 180 NVL2_SUPPORTED = False 181 JSON_PATH_BRACKETED_KEY_SUPPORTED = False 182 SUPPORTS_CREATE_TABLE_LIKE = False 183 SUPPORTS_TABLE_ALIAS_COLUMNS = False 184 SUPPORTS_TO_NUMBER = False 185 SUPPORTS_WINDOW_EXCLUDE = True 186 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False 187 SUPPORTS_MEDIAN = False 188 JSON_KEY_VALUE_PAIR_SEP = "," 189 PARSE_JSON_NAME: str | None = None 190 191 SUPPORTED_JSON_PATH_PARTS = { 192 exp.JSONPathKey, 193 exp.JSONPathRoot, 194 exp.JSONPathSubscript, 195 } 196 197 TYPE_MAPPING = { 198 **{k: v for k, v in generator.Generator.TYPE_MAPPING.items() if k != exp.DType.BLOB}, 199 exp.DType.BOOLEAN: "INTEGER", 200 exp.DType.TINYINT: "INTEGER", 201 exp.DType.SMALLINT: "INTEGER", 202 exp.DType.INT: "INTEGER", 203 exp.DType.BIGINT: "INTEGER", 204 exp.DType.FLOAT: "REAL", 205 exp.DType.DOUBLE: "REAL", 206 exp.DType.DECIMAL: "REAL", 207 exp.DType.CHAR: "TEXT", 208 exp.DType.NCHAR: "TEXT", 209 exp.DType.VARCHAR: "TEXT", 210 exp.DType.NVARCHAR: "TEXT", 211 exp.DType.BINARY: "BLOB", 212 exp.DType.VARBINARY: "BLOB", 213 } 214 215 TOKEN_MAPPING = { 216 TokenType.AUTO_INCREMENT: "AUTOINCREMENT", 217 } 218 219 TRANSFORMS = { 220 **generator.Generator.TRANSFORMS, 221 exp.AnyValue: any_value_to_max_sql, 222 exp.Chr: rename_func("CHAR"), 223 exp.CountIf: count_if_to_sum, 224 exp.Create: transforms.preprocess([_transform_create]), 225 exp.CurrentDate: lambda *_: "CURRENT_DATE", 226 exp.CurrentTime: lambda *_: "CURRENT_TIME", 227 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 228 exp.CurrentVersion: lambda *_: "SQLITE_VERSION()", 229 exp.ColumnDef: transforms.preprocess([_generated_to_auto_increment]), 230 exp.DateStrToDate: lambda self, e: self.sql(e, "this"), 231 exp.EQ: _comparison_sql("="), 232 exp.GT: _comparison_sql(">"), 233 exp.GTE: _comparison_sql(">="), 234 exp.If: rename_func("IIF"), 235 exp.ILike: no_ilike_sql, 236 exp.JSONArrayAgg: unsupported_args("order", "null_handling", "return_type", "strict")( 237 rename_func("JSON_GROUP_ARRAY") 238 ), 239 exp.JSONObjectAgg: lambda self, e: self._jsonobject_sql(e, name="JSON_GROUP_OBJECT"), 240 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")( 241 rename_func("EDITDIST3") 242 ), 243 exp.LogicalOr: rename_func("MAX"), 244 exp.LogicalAnd: rename_func("MIN"), 245 exp.LT: _comparison_sql("<"), 246 exp.LTE: _comparison_sql("<="), 247 exp.NEQ: _comparison_sql("<>"), 248 exp.NullSafeEQ: _comparison_sql("IS"), 249 exp.NullSafeNEQ: _comparison_sql("IS NOT"), 250 exp.Pivot: no_pivot_sql, 251 exp.RegexpLike: lambda self, e: self.binary(e, "REGEXP"), 252 exp.Select: transforms.preprocess( 253 [ 254 transforms.eliminate_distinct_on, 255 transforms.eliminate_qualify, 256 transforms.eliminate_semi_and_anti_joins, 257 ] 258 ), 259 exp.StrPosition: lambda self, e: strposition_sql(self, e, func_name="INSTR"), 260 exp.TableSample: no_tablesample_sql, 261 exp.TimeStrToTime: lambda self, e: self.sql(e, "this"), 262 exp.TimeToStr: lambda self, e: self.func("STRFTIME", self.format_time(e), e.this), 263 exp.TryCast: no_trycast_sql, 264 exp.TsOrDsToTimestamp: lambda self, e: self.sql(e, "this"), 265 } 266 267 # SQLite doesn't generally support CREATE TABLE .. properties 268 # https://www.sqlite.org/lang_createtable.html 269 PROPERTIES_LOCATION = { 270 **{ 271 prop: exp.Properties.Location.UNSUPPORTED 272 for prop in generator.Generator.PROPERTIES_LOCATION 273 }, 274 # There are a few exceptions (e.g. temporary tables) which are supported or 275 # can be transpiled to SQLite, so we explicitly override them accordingly 276 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 277 exp.ModuleProperty: exp.Properties.Location.POST_SCHEMA, 278 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 279 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 280 exp.VirtualProperty: exp.Properties.Location.POST_CREATE, 281 exp.WithoutRowidProperty: exp.Properties.Location.POST_SCHEMA, 282 } 283 284 LIMIT_FETCH = "LIMIT" 285 286 def root_properties(self, properties: exp.Properties) -> str: 287 return self.expressions(properties, indent=False, sep=", ") 288 289 def group_sql(self, expression: exp.Group) -> str: 290 if any(isinstance(e, exp.Tuple) and not e.expressions for e in expression.expressions): 291 select = expression.parent 292 if ( 293 len(expression.expressions) == 1 294 and not any( 295 expression.args.get(k) for k in ("grouping_sets", "cube", "rollup", "totals") 296 ) 297 and isinstance(select, exp.Select) 298 and _has_aggregate_projection(select) 299 ): 300 return "" 301 302 self.unsupported("SQLite does not support GROUP BY ()") 303 304 return super().group_sql(expression) 305 306 def offset_limit_modifiers( 307 self, expression: exp.Expr, fetch: bool, limit: exp.Fetch | exp.Limit | None 308 ) -> list[str]: 309 if expression.args.get("offset") and ( 310 not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all) 311 ): 312 limit = exp.Limit(expression=exp.Literal.number(-1)) 313 return super().offset_limit_modifiers(expression, fetch, limit) 314 315 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 316 if any(expression.args.get(key) for key in ("order", "limit", "offset")): 317 query = expression.this 318 keys = ("order", "limit", "offset", "with_") 319 # Merge grouping modifiers unless doing so would overwrite an inner clause. 320 if any(expression.args.get(key) and query.args.get(key) for key in keys): 321 query = exp.select("*").from_(query.subquery(copy=False), copy=False) 322 for key in keys: 323 if value := expression.args.get(key): 324 query.set(key, value.pop()) 325 return self.sql(query) 326 327 return super().subquery_sql(expression, sep=sep) 328 329 def autoincrementcolumnconstraint_sql( 330 self, expression: exp.AutoIncrementColumnConstraint 331 ) -> str: 332 column = expression.find_ancestor(exp.ColumnDef) 333 if column and column.find(exp.PrimaryKeyColumnConstraint): 334 return super().autoincrementcolumnconstraint_sql(expression) 335 336 self.unsupported("SQLite AUTOINCREMENT requires an INTEGER PRIMARY KEY") 337 return "" 338 339 def insert_sql(self, expression: exp.Insert) -> str: 340 if expression.args.get("ignore"): 341 expression.set("ignore", False) 342 expression.set("alternative", "IGNORE") 343 344 return super().insert_sql(expression) 345 346 def rand_sql(self, expression: exp.Rand) -> str: 347 random = self.func("RANDOM", expression.this) 348 if any(expression.args.values()): 349 return random 350 351 # Keep 53 bits so even the largest draw is exactly representable and strictly below 1 after division. 352 return f"(CAST({random} & 9007199254740991 AS REAL) / 9007199254740992)" 353 354 def bitwiseandagg_sql(self, expression: exp.BitwiseAndAgg) -> str: 355 self.unsupported("BITWISE_AND aggregation is not supported in SQLite") 356 return self.function_fallback_sql(expression) 357 358 def bitwiseoragg_sql(self, expression: exp.BitwiseOrAgg) -> str: 359 self.unsupported("BITWISE_OR aggregation is not supported in SQLite") 360 return self.function_fallback_sql(expression) 361 362 def bitwisexoragg_sql(self, expression: exp.BitwiseXorAgg) -> str: 363 self.unsupported("BITWISE_XOR aggregation is not supported in SQLite") 364 return self.function_fallback_sql(expression) 365 366 def jsonextract_sql(self, expression: exp.JSONExtract) -> str: 367 if expression.expressions: 368 return self.function_fallback_sql(expression) 369 return arrow_json_extract_sql(self, expression) 370 371 def jsonextractscalar_sql(self, expression: exp.JSONExtractScalar) -> str: 372 if expression.args.get("json_subtype"): 373 # json_extract() keeps the JSON subtype on object/array results; 374 # ->> strips it, observable when the result feeds another JSON function 375 return self.func("JSON_EXTRACT", expression.this, expression.expression) 376 return arrow_json_extract_sql(self, expression) 377 378 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 379 if expression == SQLITE_NOW: 380 # SQLite date functions accept 'now' directly and retain its milliseconds. 381 if expression.arg_key == "this" and isinstance( 382 expression.parent, (exp.Date, exp.TimeToStr) 383 ): 384 return "'now'" 385 return self.func("STRFTIME", "'%Y-%m-%d %H:%M:%f'", "'now'") 386 return super().attimezone_sql(expression) 387 388 def extract_sql(self, expression: exp.Extract) -> str: 389 part = expression.name.upper() 390 fmt = DATE_PART_FORMATS.get(part) 391 value = expression.expression 392 # PostgreSQL DATE_PART returns double precision even for integral fields. 393 if fmt and value.unnest().is_type(exp.DType.DATE) and not expression.args.get("date_part"): 394 field: exp.Expr = exp.TimeToStr(this=value.copy(), format=exp.Literal.string(fmt)) 395 if part == "QUARTER": 396 # Adding 2 to the two-digit month coerces it to an integer before division. 397 quarter = (field + 2) / 3 398 quarter.set("typed", True) 399 field = quarter 400 # Default to REAL so division preserves fractions when EXTRACT is untyped. 401 dtype = ( 402 exp.DType.INT 403 if expression.is_type(*exp.DataType.INTEGER_TYPES) 404 else exp.DType.DOUBLE 405 ) 406 return self.sql(exp.cast(field, dtype, copy=False)) 407 408 return super().extract_sql(expression) 409 410 def dateadd_sql(self, expression: exp.DateAdd) -> str: 411 return self._date_delta_sql(expression, expression.this, expression.expression) 412 413 def _date_delta_sql(self, expression: exp.Expr, base: exp.Expr, modifier: exp.Expr) -> str: 414 unit_name, modifiers = self._date_modifiers(expression, modifier) 415 # DATE + INTERVAL can return DATE or TIMESTAMP depending on the source dialect. 416 if expression.is_type(exp.DType.DATE, exp.DType.DATE32): 417 func = "DATE" 418 elif expression.is_type(exp.DType.TIME, exp.DType.TIMETZ): 419 func = "TIME" 420 elif ( 421 expression.is_type(*exp.DataType.TEMPORAL_TYPES) 422 or unit_name in ("HOUR", "MINUTE", "SECOND") 423 or isinstance(base, exp.CurrentTimestamp) 424 or base.is_type(*DATETIME_TYPES) 425 ): 426 func = "DATETIME" 427 else: 428 if unit_name in ("DAY", "WEEK", "MONTH", "QUARTER", "YEAR") and ( 429 not base.type or base.is_type(exp.DType.UNKNOWN, *exp.DataType.TEXT_TYPES) 430 ): 431 self.unsupported( 432 "SQLite DATE() may discard the time in interval arithmetic. Cast text operands " 433 "to a temporal type, or qualify untyped columns and use annotate_types " 434 "with the source schema." 435 ) 436 func = "DATE" 437 438 return self.func(func, base, *modifiers) 439 440 def _date_modifiers( 441 self, expression: exp.Expr, modifier: exp.Expr 442 ) -> tuple[str, list[exp.Expr]]: 443 unit = expression.args.get("unit") 444 # An INTERVAL amount carries its own unit, e.g. DATE_ADD(d, INTERVAL 1 DAY); 445 # unwrap it so the unit is not left inside the quoted modifier string. 446 if isinstance(modifier, exp.Interval): 447 unit = unit or modifier.unit 448 modifier = modifier.this 449 450 if isinstance(expression, (exp.Sub, exp.DateSub)): 451 modifier = self._negate_date_modifier(modifier) 452 453 # Plural units (e.g. Postgres INTERVAL '2 hours') are valid SQLite modifiers 454 unit_name = unit.name.upper().removesuffix("S") if unit else "" 455 if unit_name == "WEEK": 456 modifier = modifier * 7 457 unit = exp.var("DAY") 458 elif unit_name == "QUARTER": 459 modifier = modifier * 3 460 unit = exp.var("MONTH") 461 462 modifier = modifier.unnest() 463 if ( 464 unit 465 and not isinstance(modifier, exp.Literal) 466 and not (isinstance(modifier, exp.Neg) and modifier.this.is_number) 467 ): 468 modifier = exp.DPipe( 469 this=exp.paren(modifier), 470 expression=exp.Literal.string(f" {unit.name}"), 471 ) 472 else: 473 value = modifier.name if modifier.is_string else self.sql(modifier) 474 modifier = exp.Literal.string(f"{value} {unit.name}" if unit else value) 475 modifiers: list[exp.Expr] = [modifier] 476 if unit_name in ("MONTH", "QUARTER", "YEAR"): 477 # SQLite otherwise rolls overflowing days into the following month. 478 if self.dialect.version >= (3, 46): 479 modifiers.append(exp.Literal.string("floor")) 480 else: 481 self.unsupported("Clamping month-end interval arithmetic requires SQLite 3.46+") 482 return unit_name, modifiers 483 484 def add_sql(self, expression: exp.Add) -> str: 485 operands = _date_delta_operands(expression) 486 if operands: 487 return self._date_delta_sql(expression, *operands) 488 return super().add_sql(expression) 489 490 def sub_sql(self, expression: exp.Sub) -> str: 491 operands = _date_delta_operands(expression) 492 if operands: 493 return self._date_delta_sql(expression, *operands) 494 return super().sub_sql(expression) 495 496 def datesub_sql(self, expression: exp.DateSub) -> str: 497 return self._date_delta_sql(expression, expression.this, expression.expression) 498 499 def _negate_date_modifier(self, amount: exp.Expr) -> exp.Expr: 500 amount = amount.unnest() 501 if isinstance(amount, exp.Neg): 502 return amount.this 503 if isinstance(amount, exp.Literal): 504 text = amount.name.removeprefix("+") 505 return exp.Literal.string(text[1:] if text.startswith("-") else f"-{text}") 506 return exp.Neg( 507 this=amount 508 if isinstance(amount, (exp.Column, exp.Func)) 509 else exp.paren(amount, copy=False) 510 ) 511 512 def _coerce_date_comparison(self, *operands: exp.Expr) -> None: 513 for operand in operands: 514 value = operand.unnest() 515 # Check for interval arithmetic before inspecting the operand or cast types. 516 candidate = value 517 while isinstance(candidate, exp.Cast): 518 candidate = candidate.this.unnest() 519 if ( 520 _date_delta_operands(candidate) 521 and value.is_type(*DATETIME_TYPES) 522 and _uncast_timestamp(value) is candidate 523 ): 524 break 525 else: 526 return 527 528 values = tuple(operand.unnest() for operand in operands) 529 if not any(value.is_type(exp.DType.DATE, exp.DType.DATE32) for value in values): 530 return 531 532 # Evaluate modifiers inside JULIANDAY. An intermediate DATETIME would drop fractional seconds. 533 for operand, value in zip(operands, values): 534 modifiers: list[exp.Expr] = [] 535 while value.is_type(*DATETIME_TYPES): 536 value = _uncast_timestamp(value) 537 delta = _date_delta_operands(value) 538 if not delta or value.is_type( 539 exp.DType.DATE, exp.DType.DATE32, exp.DType.TIME, exp.DType.TIMETZ 540 ): 541 break 542 base, amount = delta 543 _, inner_modifiers = self._date_modifiers(value, amount) 544 modifiers = inner_modifiers + modifiers 545 value = base.unnest() 546 operand.replace(exp.func("JULIANDAY", value, *modifiers)) 547 548 def between_sql(self, expression: exp.Between) -> str: 549 self._coerce_date_comparison( 550 expression.this, expression.args["low"], expression.args["high"] 551 ) 552 return super().between_sql(expression) 553 554 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 555 if expression.is_type("date"): 556 return self.func("DATE", expression.this) 557 if expression.is_type(*DATETIME_TYPES): 558 return self.func("DATETIME", expression.this) 559 if expression.is_type("time"): 560 return self.func("TIME", expression.this) 561 if expression.is_type("json", "jsonb"): 562 return self.func("JSON", expression.this) 563 564 return super().cast_sql(expression) 565 566 # https://www.sqlite.org/gencol.html 567 # Inline unsupported check: mypyc cannot compile @unsupported_args on an 568 # override of an undecorated base-class method. 569 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 570 if expression.args.get("data_type"): 571 self.unsupported("SQLite generated columns do not support a data type") 572 573 this = expression.this 574 this_sql = self.sql(this) if isinstance(this, exp.Paren) else f"({self.sql(this)})" 575 storage = " STORED" if expression.args.get("persisted") else "" 576 not_null = " NOT NULL" if expression.args.get("not_null") else "" 577 return f"AS {this_sql}{storage}{not_null}" 578 579 # Note: SQLite's TRUNC always returns REAL (e.g., trunc(10.99) -> 10.0), not INTEGER. 580 # This creates a transpilation gap affecting division semantics, similar to Presto. 581 # Unlike Presto where this only affects decimals=0, SQLite has no decimals parameter 582 # so every use of TRUNC is affected. Modeling precisely would require exp.FloatTrunc. 583 @unsupported_args("decimals") 584 def trunc_sql(self, expression: exp.Trunc) -> str: 585 return self.func("TRUNC", expression.this) 586 587 def generateseries_sql(self, expression: exp.GenerateSeries) -> str: 588 parent = expression.parent 589 alias = parent and parent.args.get("alias") 590 591 if isinstance(alias, exp.TableAlias) and alias.columns: 592 column_alias = alias.columns[0] 593 alias.set("columns", None) 594 sql = self.sql( 595 exp.select(exp.alias_("value", column_alias)).from_(expression).subquery() 596 ) 597 else: 598 sql = generate_series_sql("GENERATE_SERIES")(self, expression) 599 600 return sql 601 602 def datediff_sql(self, expression: exp.DateDiff) -> str: 603 unit = expression.args.get("unit") 604 unit = unit.name.upper() if unit else "DAY" 605 606 modifier = ( 607 exp.Literal.string("start of day") 608 if unit == "DAY" and expression.args.get("date_part_boundary") 609 else None 610 ) 611 end = self.func("JULIANDAY", expression.this, modifier) 612 start = self.func("JULIANDAY", expression.expression, modifier) 613 sql = f"({end} - {start})" 614 615 if unit == "MONTH": 616 sql = f"{sql} / 30.0" 617 elif unit == "YEAR": 618 sql = f"{sql} / 365.0" 619 elif unit == "HOUR": 620 sql = f"{sql} * 24.0" 621 elif unit == "MINUTE": 622 sql = f"{sql} * 1440.0" 623 elif unit == "SECOND": 624 sql = f"{sql} * 86400.0" 625 elif unit == "MILLISECOND": 626 sql = f"{sql} * 86400000.0" 627 elif unit == "MICROSECOND": 628 sql = f"{sql} * 86400000000.0" 629 elif unit == "NANOSECOND": 630 sql = f"{sql} * 86400000000000.0" 631 elif unit != "DAY": 632 self.unsupported(f"DATEDIFF unsupported for '{unit}'.") 633 634 return f"CAST({sql} AS INTEGER)" 635 636 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 637 node = expression.parent if isinstance(expression.parent, exp.Filter) else expression 638 window = node.parent 639 640 if ( 641 isinstance(expression.this, exp.Order) 642 and isinstance(window, exp.Window) 643 and window.this is node 644 ): 645 self.unsupported( 646 "SQLite GROUP_CONCAT window functions do not support argument ORDER BY" 647 ) 648 expression.set("this", expression.this.this) 649 650 this = expression.this 651 if isinstance(this, exp.Order): 652 this = this.this 653 if isinstance(this, exp.Distinct) and expression.args.get( 654 "separator" 655 ) == exp.Literal.string(","): 656 # DISTINCT aggregates accept one argument; SQLite already defaults to a comma separator. 657 expression.set("separator", None) 658 659 return groupconcat_sql( 660 self, expression, func_name="GROUP_CONCAT", sep=None, within_group=False 661 ) 662 663 def _greatest_least_sql(self, expression: exp.Greatest | exp.Least) -> str: 664 if not expression.expressions: 665 return self.sql(expression, "this") 666 667 name = "MAX" if isinstance(expression, exp.Greatest) else "MIN" 668 669 if not expression.args.get("ignore_nulls"): 670 return rename_func(name)(self, expression) 671 672 # SQLite's multi-argument MAX/MIN return NULL if any argument is NULL. 673 # GREATEST(a, b, c) -> MAX(COALESCE(a, b, c), COALESCE(b, c, a), COALESCE(c, a, b)). 674 args = [expression.this, *expression.expressions] 675 676 coalesces = [] 677 for i in range(len(args)): 678 rotated = args[i:] + args[:i] 679 coalesces.append(exp.Coalesce(this=rotated[0], expressions=rotated[1:])) 680 681 return self.func(name, *coalesces) 682 683 def greatest_sql(self, expression: exp.Greatest) -> str: 684 return self._greatest_least_sql(expression) 685 686 def least_sql(self, expression: exp.Least) -> str: 687 return self._greatest_least_sql(expression) 688 689 def transaction_sql(self, expression: exp.Transaction) -> str: 690 this = expression.this 691 this = f" {this}" if this else "" 692 return f"BEGIN{this} TRANSACTION" 693 694 def isascii_sql(self, expression: exp.IsAscii) -> str: 695 return f"(NOT {self.sql(expression.this)} GLOB CAST(x'2a5b5e012d7f5d2a' AS TEXT))" 696 697 @unsupported_args("this") 698 def currentschema_sql(self, expression: exp.CurrentSchema) -> str: 699 return "'main'" 700 701 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 702 self.unsupported("SQLite does not support IGNORE NULLS.") 703 return self.sql(expression.this) 704 705 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 706 return self.sql(expression.this) 707 708 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 709 if ( 710 expression.text("kind").upper() == "RANGE" 711 and expression.text("start").upper() == "CURRENT ROW" 712 and expression.args.get("end") is None 713 ): 714 return "RANGE CURRENT ROW" 715 716 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
WHEREclause. 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
SUPPORTED_JSON_PATH_PARTS =
{<class 'sqlglot.expressions.query.JSONPathRoot'>, <class 'sqlglot.expressions.query.JSONPathSubscript'>, <class 'sqlglot.expressions.query.JSONPathKey'>}
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'}
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.BinaryColumnConstraint'>: <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.CopyTagsProperty'>: <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.IgnoreGrantsProperty'>: <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.JSONBContainsTopKey'>: <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.WithoutRowidProperty'>: <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.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.core.EQ'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.core.GT'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.core.GTE'>: <function _comparison_sql.<locals>._sql>, <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.core.LT'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.core.LTE'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.core.NEQ'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.core.NullSafeEQ'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.core.NullSafeNEQ'>: <function _comparison_sql.<locals>._sql>, <class 'sqlglot.expressions.query.Pivot'>: <function no_pivot_sql>, <class 'sqlglot.expressions.core.RegexpLike'>: <function SQLiteGenerator.<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.AggregateKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <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.properties.CopyTagsProperty'>: <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.IgnoreGrantsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.IncludeProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.InteractiveProperty'>: <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.properties.OptionsProperty'>: <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.properties.PhysicalProperty'>: <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.StorageProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StrictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Tags'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TableSpaceProperty'>: <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.WithoutRowidProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ForceProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>}
289 def group_sql(self, expression: exp.Group) -> str: 290 if any(isinstance(e, exp.Tuple) and not e.expressions for e in expression.expressions): 291 select = expression.parent 292 if ( 293 len(expression.expressions) == 1 294 and not any( 295 expression.args.get(k) for k in ("grouping_sets", "cube", "rollup", "totals") 296 ) 297 and isinstance(select, exp.Select) 298 and _has_aggregate_projection(select) 299 ): 300 return "" 301 302 self.unsupported("SQLite does not support GROUP BY ()") 303 304 return super().group_sql(expression)
def
offset_limit_modifiers( self, expression: sqlglot.expressions.core.Expr, fetch: bool, limit: sqlglot.expressions.query.Fetch | sqlglot.expressions.query.Limit | None) -> list[str]:
306 def offset_limit_modifiers( 307 self, expression: exp.Expr, fetch: bool, limit: exp.Fetch | exp.Limit | None 308 ) -> list[str]: 309 if expression.args.get("offset") and ( 310 not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all) 311 ): 312 limit = exp.Limit(expression=exp.Literal.number(-1)) 313 return super().offset_limit_modifiers(expression, fetch, limit)
315 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 316 if any(expression.args.get(key) for key in ("order", "limit", "offset")): 317 query = expression.this 318 keys = ("order", "limit", "offset", "with_") 319 # Merge grouping modifiers unless doing so would overwrite an inner clause. 320 if any(expression.args.get(key) and query.args.get(key) for key in keys): 321 query = exp.select("*").from_(query.subquery(copy=False), copy=False) 322 for key in keys: 323 if value := expression.args.get(key): 324 query.set(key, value.pop()) 325 return self.sql(query) 326 327 return super().subquery_sql(expression, sep=sep)
def
autoincrementcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.AutoIncrementColumnConstraint) -> str:
329 def autoincrementcolumnconstraint_sql( 330 self, expression: exp.AutoIncrementColumnConstraint 331 ) -> str: 332 column = expression.find_ancestor(exp.ColumnDef) 333 if column and column.find(exp.PrimaryKeyColumnConstraint): 334 return super().autoincrementcolumnconstraint_sql(expression) 335 336 self.unsupported("SQLite AUTOINCREMENT requires an INTEGER PRIMARY KEY") 337 return ""
346 def rand_sql(self, expression: exp.Rand) -> str: 347 random = self.func("RANDOM", expression.this) 348 if any(expression.args.values()): 349 return random 350 351 # Keep 53 bits so even the largest draw is exactly representable and strictly below 1 after division. 352 return f"(CAST({random} & 9007199254740991 AS REAL) / 9007199254740992)"
371 def jsonextractscalar_sql(self, expression: exp.JSONExtractScalar) -> str: 372 if expression.args.get("json_subtype"): 373 # json_extract() keeps the JSON subtype on object/array results; 374 # ->> strips it, observable when the result feeds another JSON function 375 return self.func("JSON_EXTRACT", expression.this, expression.expression) 376 return arrow_json_extract_sql(self, expression)
378 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 379 if expression == SQLITE_NOW: 380 # SQLite date functions accept 'now' directly and retain its milliseconds. 381 if expression.arg_key == "this" and isinstance( 382 expression.parent, (exp.Date, exp.TimeToStr) 383 ): 384 return "'now'" 385 return self.func("STRFTIME", "'%Y-%m-%d %H:%M:%f'", "'now'") 386 return super().attimezone_sql(expression)
388 def extract_sql(self, expression: exp.Extract) -> str: 389 part = expression.name.upper() 390 fmt = DATE_PART_FORMATS.get(part) 391 value = expression.expression 392 # PostgreSQL DATE_PART returns double precision even for integral fields. 393 if fmt and value.unnest().is_type(exp.DType.DATE) and not expression.args.get("date_part"): 394 field: exp.Expr = exp.TimeToStr(this=value.copy(), format=exp.Literal.string(fmt)) 395 if part == "QUARTER": 396 # Adding 2 to the two-digit month coerces it to an integer before division. 397 quarter = (field + 2) / 3 398 quarter.set("typed", True) 399 field = quarter 400 # Default to REAL so division preserves fractions when EXTRACT is untyped. 401 dtype = ( 402 exp.DType.INT 403 if expression.is_type(*exp.DataType.INTEGER_TYPES) 404 else exp.DType.DOUBLE 405 ) 406 return self.sql(exp.cast(field, dtype, copy=False)) 407 408 return super().extract_sql(expression)
def
cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
554 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 555 if expression.is_type("date"): 556 return self.func("DATE", expression.this) 557 if expression.is_type(*DATETIME_TYPES): 558 return self.func("DATETIME", expression.this) 559 if expression.is_type("time"): 560 return self.func("TIME", expression.this) 561 if expression.is_type("json", "jsonb"): 562 return self.func("JSON", expression.this) 563 564 return super().cast_sql(expression)
def
computedcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.ComputedColumnConstraint) -> str:
569 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 570 if expression.args.get("data_type"): 571 self.unsupported("SQLite generated columns do not support a data type") 572 573 this = expression.this 574 this_sql = self.sql(this) if isinstance(this, exp.Paren) else f"({self.sql(this)})" 575 storage = " STORED" if expression.args.get("persisted") else "" 576 not_null = " NOT NULL" if expression.args.get("not_null") else "" 577 return f"AS {this_sql}{storage}{not_null}"
@unsupported_args('decimals')
def
trunc_sql(self, expression: sqlglot.expressions.math.Trunc) -> str:
587 def generateseries_sql(self, expression: exp.GenerateSeries) -> str: 588 parent = expression.parent 589 alias = parent and parent.args.get("alias") 590 591 if isinstance(alias, exp.TableAlias) and alias.columns: 592 column_alias = alias.columns[0] 593 alias.set("columns", None) 594 sql = self.sql( 595 exp.select(exp.alias_("value", column_alias)).from_(expression).subquery() 596 ) 597 else: 598 sql = generate_series_sql("GENERATE_SERIES")(self, expression) 599 600 return sql
602 def datediff_sql(self, expression: exp.DateDiff) -> str: 603 unit = expression.args.get("unit") 604 unit = unit.name.upper() if unit else "DAY" 605 606 modifier = ( 607 exp.Literal.string("start of day") 608 if unit == "DAY" and expression.args.get("date_part_boundary") 609 else None 610 ) 611 end = self.func("JULIANDAY", expression.this, modifier) 612 start = self.func("JULIANDAY", expression.expression, modifier) 613 sql = f"({end} - {start})" 614 615 if unit == "MONTH": 616 sql = f"{sql} / 30.0" 617 elif unit == "YEAR": 618 sql = f"{sql} / 365.0" 619 elif unit == "HOUR": 620 sql = f"{sql} * 24.0" 621 elif unit == "MINUTE": 622 sql = f"{sql} * 1440.0" 623 elif unit == "SECOND": 624 sql = f"{sql} * 86400.0" 625 elif unit == "MILLISECOND": 626 sql = f"{sql} * 86400000.0" 627 elif unit == "MICROSECOND": 628 sql = f"{sql} * 86400000000.0" 629 elif unit == "NANOSECOND": 630 sql = f"{sql} * 86400000000000.0" 631 elif unit != "DAY": 632 self.unsupported(f"DATEDIFF unsupported for '{unit}'.") 633 634 return f"CAST({sql} AS INTEGER)"
636 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 637 node = expression.parent if isinstance(expression.parent, exp.Filter) else expression 638 window = node.parent 639 640 if ( 641 isinstance(expression.this, exp.Order) 642 and isinstance(window, exp.Window) 643 and window.this is node 644 ): 645 self.unsupported( 646 "SQLite GROUP_CONCAT window functions do not support argument ORDER BY" 647 ) 648 expression.set("this", expression.this.this) 649 650 this = expression.this 651 if isinstance(this, exp.Order): 652 this = this.this 653 if isinstance(this, exp.Distinct) and expression.args.get( 654 "separator" 655 ) == exp.Literal.string(","): 656 # DISTINCT aggregates accept one argument; SQLite already defaults to a comma separator. 657 expression.set("separator", None) 658 659 return groupconcat_sql( 660 self, expression, func_name="GROUP_CONCAT", sep=None, within_group=False 661 )
@unsupported_args('this')
def
currentschema_sql(self, expression: sqlglot.expressions.functions.CurrentSchema) -> str:
708 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 709 if ( 710 expression.text("kind").upper() == "RANGE" 711 and expression.text("start").upper() == "CURRENT ROW" 712 and expression.args.get("end") is None 713 ): 714 return "RANGE CURRENT ROW" 715 716 return super().windowspec_sql(expression)
Inherited Members
- sqlglot.generator.Generator
- Generator
- NULL_ORDERING_SUPPORTED
- WINDOW_FUNCS_WITH_NULL_ORDERING
- WINDOW_FUNCS_REQUIRING_ORDER
- IGNORE_NULLS_IN_FUNC
- IGNORE_NULLS_BEFORE_ORDER
- LOCKING_READS_SUPPORTED
- WRAP_DERIVED_VALUES
- CREATE_FUNCTION_RETURN_AS
- MATCHED_BY_SOURCE
- SUPPORTS_MERGE_WHERE
- MERGE_SCHEMA_EVOLUTION_MIN_VERSION
- MERGE_ALL_BY_NAME
- SINGLE_STRING_INTERVAL
- INTERVAL_ALLOWS_PLURAL_FORM
- AUTO_REFRESH_BARE_INTERVALS
- LIMIT_ONLY_LITERALS
- RENAME_TABLE_WITH_DB
- GROUPINGS_SEP
- SUPPORTS_GROUPING_SETS_AS_SUFFIX
- INDEX_ON
- INOUT_SEPARATOR
- DIRECTED_JOINS
- SUPPORTS_NEAREST_JOIN
- SUPPORTS_MATCH_CONDITION
- MATCH_CONDITION_IN_ON
- QUERY_HINT_SEP
- IS_BOOL_ALLOWED
- CAST_TO_INT_ROUNDS
- SAFE_INT_DIVISION
- INT_DIV_OPERATOR
- 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
- ALTER_TABLE_ADD_COLUMNS_WRAPPED
- 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_OPTIMIZE
- SUPPORTS_EXECUTE_IMMEDIATE
- 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
- SUPPORTS_NESTED_JSON_SELECT
- JSON_PATH_SINGLE_QUOTE_ESCAPE
- JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
- CAN_IMPLEMENT_ARRAY_ANY
- SET_OP_MODIFIERS
- SET_OP_LIMITS
- COPY_PARAMS_ARE_WRAPPED
- COPY_PARAMS_EQ_REQUIRED
- COPY_HAS_INTO_KEYWORD
- UNICODE_SUBSTITUTE
- STAR_EXCEPT
- HEX_FUNC
- BYTE_STRING_FUNCTION
- 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
- DAYOFWEEK_NAME
- DAYOFWEEK_ZERO_BASED
- VARIANCE_NAME
- VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE
- ALTER_SET_TYPE
- ARRAY_SIZE_DIM_REQUIRED
- SUPPORTS_MULTI_ARG_CHR
- 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
- MOD_OPERATOR
- BARE_OPERATORS
- MOD_PAREN_PARENT_TYPES
- ALTER_PARTITION_OPTIONS
- 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
- 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
- per_sql
- hint_sql
- indexparameters_sql
- index_sql
- dynamicidentifier_sql
- identifier_sql
- hex_sql
- lowerhex_sql
- inputoutputformat_sql
- national_sql
- partition_sql
- properties_sql
- 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
- lockingstatement_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
- tableargument_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
- having_sql
- connectto_sql
- disconnect_sql
- connect_sql
- prior_sql
- join_sql
- nearest_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
- after_limit_modifiers
- select_sql
- schema_sql
- schema_columns_sql
- star_sql
- parameter_sql
- sessionparameter_sql
- placeholder_sql
- qualify_sql
- unnest_sql
- prewhere_sql
- where_sql
- window_sql
- partition_by_sql
- partitionbyexcluding_sql
- withingroup_sql
- bracket_offset_expressions
- bracket_sql
- all_sql
- any_sql
- exists_sql
- case_sql
- constraint_sql
- nextvaluefor_sql
- dayofweek_sql
- extract_date_part
- 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
- format_sql
- formatjson_sql
- formatphrase_sql
- teradataconversion_sql
- teradatatitle_sql
- teradatanamed_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
- pos_sql
- neg_sql
- not_sql
- alias_sql
- pivotalias_sql
- aliases_sql
- atindex_sql
- fromtimezone_sql
- fromiso8601date_sql
- fromiso8601timestamp_sql
- fromiso8601timestampnanos_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
- optimize_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
- replacecolumns_sql
- addpartition_sql
- distinct_sql
- havingmax_sql
- intdiv_sql
- dpipe_sql
- nullif_zero_divisor
- div_sql
- safedivide_sql
- overlaps_sql
- distance_sql
- distancend_sql
- dot_sql
- nestedjsonselect_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
- trycast_sql
- jsoncast_sql
- try_sql
- log_sql
- use_sql
- binary
- ceil_floor
- function_fallback_sql
- function_name
- 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
- aggregatekeyproperty_sql
- duplicatekeyproperty_sql
- uniquekeyproperty_sql
- distributedbyproperty_sql
- oncluster_sql
- clusteredbyproperty_sql
- anyvalue_sql
- querytransform_sql
- indexconstraintoption_sql
- checkcolumnconstraint_sql
- indexcolumnconstraint_sql
- nvl2_sql
- nthvalue_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
- arrayinsert_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
- 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
- min_sql
- max_sql
- arrayagg_sql
- timeslice_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
- arraysort_sql
- variance_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
- liststage_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
- datetrunc_sql
- chr_sql
- weightstring_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
- executeimmediate_sql
- altermodifysqlsecurity_sql
- usingproperty_sql
- renameindex_sql