sqlglot.dialects.presto
1from __future__ import annotations 2 3from sqlglot import exp, generator, parser, tokens, transforms 4from sqlglot.dialects.dialect import ( 5 Dialect, 6 date_trunc_to_time, 7 format_time_lambda, 8 if_sql, 9 no_ilike_sql, 10 no_safe_divide_sql, 11 rename_func, 12 struct_extract_sql, 13 timestamptrunc_sql, 14 timestrtotime_sql, 15) 16from sqlglot.dialects.mysql import MySQL 17from sqlglot.errors import UnsupportedError 18from sqlglot.helper import seq_get 19from sqlglot.tokens import TokenType 20 21 22def _approx_distinct_sql(self, expression): 23 accuracy = expression.args.get("accuracy") 24 accuracy = ", " + self.sql(accuracy) if accuracy else "" 25 return f"APPROX_DISTINCT({self.sql(expression, 'this')}{accuracy})" 26 27 28def _datatype_sql(self, expression): 29 sql = self.datatype_sql(expression) 30 if expression.this == exp.DataType.Type.TIMESTAMPTZ: 31 sql = f"{sql} WITH TIME ZONE" 32 return sql 33 34 35def _explode_to_unnest_sql(self, expression): 36 if isinstance(expression.this, (exp.Explode, exp.Posexplode)): 37 return self.sql( 38 exp.Join( 39 this=exp.Unnest( 40 expressions=[expression.this.this], 41 alias=expression.args.get("alias"), 42 ordinality=isinstance(expression.this, exp.Posexplode), 43 ), 44 kind="cross", 45 ) 46 ) 47 return self.lateral_sql(expression) 48 49 50def _initcap_sql(self, expression): 51 regex = r"(\w)(\w*)" 52 return f"REGEXP_REPLACE({self.sql(expression, 'this')}, '{regex}', x -> UPPER(x[1]) || LOWER(x[2]))" 53 54 55def _decode_sql(self, expression): 56 _ensure_utf8(expression.args.get("charset")) 57 return self.func("FROM_UTF8", expression.this, expression.args.get("replace")) 58 59 60def _encode_sql(self, expression): 61 _ensure_utf8(expression.args.get("charset")) 62 return f"TO_UTF8({self.sql(expression, 'this')})" 63 64 65def _no_sort_array(self, expression): 66 if expression.args.get("asc") == exp.false(): 67 comparator = "(a, b) -> CASE WHEN a < b THEN 1 WHEN a > b THEN -1 ELSE 0 END" 68 else: 69 comparator = None 70 return self.func("ARRAY_SORT", expression.this, comparator) 71 72 73def _schema_sql(self, expression): 74 if isinstance(expression.parent, exp.Property): 75 columns = ", ".join(f"'{c.name}'" for c in expression.expressions) 76 return f"ARRAY[{columns}]" 77 78 for schema in expression.parent.find_all(exp.Schema): 79 if isinstance(schema.parent, exp.Property): 80 expression = expression.copy() 81 expression.expressions.extend(schema.expressions) 82 83 return self.schema_sql(expression) 84 85 86def _quantile_sql(self, expression): 87 self.unsupported("Presto does not support exact quantiles") 88 return f"APPROX_PERCENTILE({self.sql(expression, 'this')}, {self.sql(expression, 'quantile')})" 89 90 91def _str_to_time_sql(self, expression): 92 return f"DATE_PARSE({self.sql(expression, 'this')}, {self.format_time(expression)})" 93 94 95def _ts_or_ds_to_date_sql(self, expression): 96 time_format = self.format_time(expression) 97 if time_format and time_format not in (Presto.time_format, Presto.date_format): 98 return f"CAST({_str_to_time_sql(self, expression)} AS DATE)" 99 return f"CAST(SUBSTR(CAST({self.sql(expression, 'this')} AS VARCHAR), 1, 10) AS DATE)" 100 101 102def _ts_or_ds_add_sql(self, expression): 103 return self.func( 104 "DATE_ADD", 105 exp.Literal.string(expression.text("unit") or "day"), 106 expression.expression, 107 self.func( 108 "DATE_PARSE", 109 self.func("SUBSTR", expression.this, exp.Literal.number(1), exp.Literal.number(10)), 110 Presto.date_format, 111 ), 112 ) 113 114 115def _sequence_sql(self, expression): 116 start = expression.args["start"] 117 end = expression.args["end"] 118 step = expression.args.get("step", 1) # Postgres defaults to 1 for generate_series 119 120 target_type = None 121 122 if isinstance(start, exp.Cast): 123 target_type = start.to 124 elif isinstance(end, exp.Cast): 125 target_type = end.to 126 127 if target_type and target_type.this == exp.DataType.Type.TIMESTAMP: 128 to = target_type.copy() 129 130 if target_type is start.to: 131 end = exp.Cast(this=end, to=to) 132 else: 133 start = exp.Cast(this=start, to=to) 134 135 return self.func("SEQUENCE", start, end, step) 136 137 138def _ensure_utf8(charset): 139 if charset.name.lower() != "utf-8": 140 raise UnsupportedError(f"Unsupported charset {charset}") 141 142 143def _approx_percentile(args): 144 if len(args) == 4: 145 return exp.ApproxQuantile( 146 this=seq_get(args, 0), 147 weight=seq_get(args, 1), 148 quantile=seq_get(args, 2), 149 accuracy=seq_get(args, 3), 150 ) 151 if len(args) == 3: 152 return exp.ApproxQuantile( 153 this=seq_get(args, 0), 154 quantile=seq_get(args, 1), 155 accuracy=seq_get(args, 2), 156 ) 157 return exp.ApproxQuantile.from_arg_list(args) 158 159 160def _from_unixtime(args): 161 if len(args) == 3: 162 return exp.UnixToTime( 163 this=seq_get(args, 0), 164 hours=seq_get(args, 1), 165 minutes=seq_get(args, 2), 166 ) 167 if len(args) == 2: 168 return exp.UnixToTime( 169 this=seq_get(args, 0), 170 zone=seq_get(args, 1), 171 ) 172 return exp.UnixToTime.from_arg_list(args) 173 174 175class Presto(Dialect): 176 index_offset = 1 177 null_ordering = "nulls_are_last" 178 time_format = MySQL.time_format # type: ignore 179 time_mapping = MySQL.time_mapping # type: ignore 180 181 class Tokenizer(tokens.Tokenizer): 182 KEYWORDS = { 183 **tokens.Tokenizer.KEYWORDS, 184 "START": TokenType.BEGIN, 185 "ROW": TokenType.STRUCT, 186 } 187 188 class Parser(parser.Parser): 189 FUNCTIONS = { 190 **parser.Parser.FUNCTIONS, # type: ignore 191 "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list, 192 "CARDINALITY": exp.ArraySize.from_arg_list, 193 "CONTAINS": exp.ArrayContains.from_arg_list, 194 "DATE_ADD": lambda args: exp.DateAdd( 195 this=seq_get(args, 2), 196 expression=seq_get(args, 1), 197 unit=seq_get(args, 0), 198 ), 199 "DATE_DIFF": lambda args: exp.DateDiff( 200 this=seq_get(args, 2), 201 expression=seq_get(args, 1), 202 unit=seq_get(args, 0), 203 ), 204 "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"), 205 "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"), 206 "DATE_TRUNC": date_trunc_to_time, 207 "FROM_UNIXTIME": _from_unixtime, 208 "NOW": exp.CurrentTimestamp.from_arg_list, 209 "STRPOS": lambda args: exp.StrPosition( 210 this=seq_get(args, 0), 211 substr=seq_get(args, 1), 212 instance=seq_get(args, 2), 213 ), 214 "TO_UNIXTIME": exp.TimeToUnix.from_arg_list, 215 "APPROX_PERCENTILE": _approx_percentile, 216 "FROM_HEX": exp.Unhex.from_arg_list, 217 "TO_HEX": exp.Hex.from_arg_list, 218 "TO_UTF8": lambda args: exp.Encode( 219 this=seq_get(args, 0), charset=exp.Literal.string("utf-8") 220 ), 221 "FROM_UTF8": lambda args: exp.Decode( 222 this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8") 223 ), 224 } 225 FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy() 226 FUNCTION_PARSERS.pop("TRIM") 227 228 class Generator(generator.Generator): 229 STRUCT_DELIMITER = ("(", ")") 230 231 PROPERTIES_LOCATION = { 232 **generator.Generator.PROPERTIES_LOCATION, # type: ignore 233 exp.LocationProperty: exp.Properties.Location.UNSUPPORTED, 234 } 235 236 TYPE_MAPPING = { 237 **generator.Generator.TYPE_MAPPING, # type: ignore 238 exp.DataType.Type.INT: "INTEGER", 239 exp.DataType.Type.FLOAT: "REAL", 240 exp.DataType.Type.BINARY: "VARBINARY", 241 exp.DataType.Type.TEXT: "VARCHAR", 242 exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP", 243 exp.DataType.Type.STRUCT: "ROW", 244 } 245 246 TRANSFORMS = { 247 **generator.Generator.TRANSFORMS, # type: ignore 248 **transforms.UNALIAS_GROUP, # type: ignore 249 **transforms.ELIMINATE_QUALIFY, # type: ignore 250 exp.ApproxDistinct: _approx_distinct_sql, 251 exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]", 252 exp.ArrayConcat: rename_func("CONCAT"), 253 exp.ArrayContains: rename_func("CONTAINS"), 254 exp.ArraySize: rename_func("CARDINALITY"), 255 exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 256 exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 257 exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})", 258 exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 259 exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 260 exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 261 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 262 exp.DataType: _datatype_sql, 263 exp.DateAdd: lambda self, e: self.func( 264 "DATE_ADD", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this 265 ), 266 exp.DateDiff: lambda self, e: self.func( 267 "DATE_DIFF", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this 268 ), 269 exp.DateStrToDate: lambda self, e: f"CAST(DATE_PARSE({self.sql(e, 'this')}, {Presto.date_format}) AS DATE)", 270 exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.dateint_format}) AS INT)", 271 exp.Decode: _decode_sql, 272 exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.dateint_format}) AS DATE)", 273 exp.Encode: _encode_sql, 274 exp.GenerateSeries: _sequence_sql, 275 exp.Hex: rename_func("TO_HEX"), 276 exp.If: if_sql, 277 exp.ILike: no_ilike_sql, 278 exp.Initcap: _initcap_sql, 279 exp.Lateral: _explode_to_unnest_sql, 280 exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"), 281 exp.LogicalOr: rename_func("BOOL_OR"), 282 exp.LogicalAnd: rename_func("BOOL_AND"), 283 exp.Quantile: _quantile_sql, 284 exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"), 285 exp.SafeDivide: no_safe_divide_sql, 286 exp.Schema: _schema_sql, 287 exp.SortArray: _no_sort_array, 288 exp.StrPosition: rename_func("STRPOS"), 289 exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)", 290 exp.StrToTime: _str_to_time_sql, 291 exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))", 292 exp.StructExtract: struct_extract_sql, 293 exp.TableFormatProperty: lambda self, e: f"TABLE_FORMAT='{e.name.upper()}'", 294 exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'", 295 exp.TimestampTrunc: timestamptrunc_sql, 296 exp.TimeStrToDate: timestrtotime_sql, 297 exp.TimeStrToTime: timestrtotime_sql, 298 exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.time_format}))", 299 exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 300 exp.TimeToUnix: rename_func("TO_UNIXTIME"), 301 exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)", 302 exp.TsOrDsAdd: _ts_or_ds_add_sql, 303 exp.TsOrDsToDate: _ts_or_ds_to_date_sql, 304 exp.Unhex: rename_func("FROM_HEX"), 305 exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})", 306 exp.UnixToTime: rename_func("FROM_UNIXTIME"), 307 exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)", 308 exp.VariancePop: rename_func("VAR_POP"), 309 } 310 311 def transaction_sql(self, expression): 312 modes = expression.args.get("modes") 313 modes = f" {', '.join(modes)}" if modes else "" 314 return f"START TRANSACTION{modes}"
176class Presto(Dialect): 177 index_offset = 1 178 null_ordering = "nulls_are_last" 179 time_format = MySQL.time_format # type: ignore 180 time_mapping = MySQL.time_mapping # type: ignore 181 182 class Tokenizer(tokens.Tokenizer): 183 KEYWORDS = { 184 **tokens.Tokenizer.KEYWORDS, 185 "START": TokenType.BEGIN, 186 "ROW": TokenType.STRUCT, 187 } 188 189 class Parser(parser.Parser): 190 FUNCTIONS = { 191 **parser.Parser.FUNCTIONS, # type: ignore 192 "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list, 193 "CARDINALITY": exp.ArraySize.from_arg_list, 194 "CONTAINS": exp.ArrayContains.from_arg_list, 195 "DATE_ADD": lambda args: exp.DateAdd( 196 this=seq_get(args, 2), 197 expression=seq_get(args, 1), 198 unit=seq_get(args, 0), 199 ), 200 "DATE_DIFF": lambda args: exp.DateDiff( 201 this=seq_get(args, 2), 202 expression=seq_get(args, 1), 203 unit=seq_get(args, 0), 204 ), 205 "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"), 206 "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"), 207 "DATE_TRUNC": date_trunc_to_time, 208 "FROM_UNIXTIME": _from_unixtime, 209 "NOW": exp.CurrentTimestamp.from_arg_list, 210 "STRPOS": lambda args: exp.StrPosition( 211 this=seq_get(args, 0), 212 substr=seq_get(args, 1), 213 instance=seq_get(args, 2), 214 ), 215 "TO_UNIXTIME": exp.TimeToUnix.from_arg_list, 216 "APPROX_PERCENTILE": _approx_percentile, 217 "FROM_HEX": exp.Unhex.from_arg_list, 218 "TO_HEX": exp.Hex.from_arg_list, 219 "TO_UTF8": lambda args: exp.Encode( 220 this=seq_get(args, 0), charset=exp.Literal.string("utf-8") 221 ), 222 "FROM_UTF8": lambda args: exp.Decode( 223 this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8") 224 ), 225 } 226 FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy() 227 FUNCTION_PARSERS.pop("TRIM") 228 229 class Generator(generator.Generator): 230 STRUCT_DELIMITER = ("(", ")") 231 232 PROPERTIES_LOCATION = { 233 **generator.Generator.PROPERTIES_LOCATION, # type: ignore 234 exp.LocationProperty: exp.Properties.Location.UNSUPPORTED, 235 } 236 237 TYPE_MAPPING = { 238 **generator.Generator.TYPE_MAPPING, # type: ignore 239 exp.DataType.Type.INT: "INTEGER", 240 exp.DataType.Type.FLOAT: "REAL", 241 exp.DataType.Type.BINARY: "VARBINARY", 242 exp.DataType.Type.TEXT: "VARCHAR", 243 exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP", 244 exp.DataType.Type.STRUCT: "ROW", 245 } 246 247 TRANSFORMS = { 248 **generator.Generator.TRANSFORMS, # type: ignore 249 **transforms.UNALIAS_GROUP, # type: ignore 250 **transforms.ELIMINATE_QUALIFY, # type: ignore 251 exp.ApproxDistinct: _approx_distinct_sql, 252 exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]", 253 exp.ArrayConcat: rename_func("CONCAT"), 254 exp.ArrayContains: rename_func("CONTAINS"), 255 exp.ArraySize: rename_func("CARDINALITY"), 256 exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 257 exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 258 exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})", 259 exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 260 exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 261 exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 262 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 263 exp.DataType: _datatype_sql, 264 exp.DateAdd: lambda self, e: self.func( 265 "DATE_ADD", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this 266 ), 267 exp.DateDiff: lambda self, e: self.func( 268 "DATE_DIFF", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this 269 ), 270 exp.DateStrToDate: lambda self, e: f"CAST(DATE_PARSE({self.sql(e, 'this')}, {Presto.date_format}) AS DATE)", 271 exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.dateint_format}) AS INT)", 272 exp.Decode: _decode_sql, 273 exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.dateint_format}) AS DATE)", 274 exp.Encode: _encode_sql, 275 exp.GenerateSeries: _sequence_sql, 276 exp.Hex: rename_func("TO_HEX"), 277 exp.If: if_sql, 278 exp.ILike: no_ilike_sql, 279 exp.Initcap: _initcap_sql, 280 exp.Lateral: _explode_to_unnest_sql, 281 exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"), 282 exp.LogicalOr: rename_func("BOOL_OR"), 283 exp.LogicalAnd: rename_func("BOOL_AND"), 284 exp.Quantile: _quantile_sql, 285 exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"), 286 exp.SafeDivide: no_safe_divide_sql, 287 exp.Schema: _schema_sql, 288 exp.SortArray: _no_sort_array, 289 exp.StrPosition: rename_func("STRPOS"), 290 exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)", 291 exp.StrToTime: _str_to_time_sql, 292 exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))", 293 exp.StructExtract: struct_extract_sql, 294 exp.TableFormatProperty: lambda self, e: f"TABLE_FORMAT='{e.name.upper()}'", 295 exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'", 296 exp.TimestampTrunc: timestamptrunc_sql, 297 exp.TimeStrToDate: timestrtotime_sql, 298 exp.TimeStrToTime: timestrtotime_sql, 299 exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.time_format}))", 300 exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 301 exp.TimeToUnix: rename_func("TO_UNIXTIME"), 302 exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)", 303 exp.TsOrDsAdd: _ts_or_ds_add_sql, 304 exp.TsOrDsToDate: _ts_or_ds_to_date_sql, 305 exp.Unhex: rename_func("FROM_HEX"), 306 exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})", 307 exp.UnixToTime: rename_func("FROM_UNIXTIME"), 308 exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)", 309 exp.VariancePop: rename_func("VAR_POP"), 310 } 311 312 def transaction_sql(self, expression): 313 modes = expression.args.get("modes") 314 modes = f" {', '.join(modes)}" if modes else "" 315 return f"START TRANSACTION{modes}"
182 class Tokenizer(tokens.Tokenizer): 183 KEYWORDS = { 184 **tokens.Tokenizer.KEYWORDS, 185 "START": TokenType.BEGIN, 186 "ROW": TokenType.STRUCT, 187 }
Inherited Members
189 class Parser(parser.Parser): 190 FUNCTIONS = { 191 **parser.Parser.FUNCTIONS, # type: ignore 192 "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list, 193 "CARDINALITY": exp.ArraySize.from_arg_list, 194 "CONTAINS": exp.ArrayContains.from_arg_list, 195 "DATE_ADD": lambda args: exp.DateAdd( 196 this=seq_get(args, 2), 197 expression=seq_get(args, 1), 198 unit=seq_get(args, 0), 199 ), 200 "DATE_DIFF": lambda args: exp.DateDiff( 201 this=seq_get(args, 2), 202 expression=seq_get(args, 1), 203 unit=seq_get(args, 0), 204 ), 205 "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"), 206 "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"), 207 "DATE_TRUNC": date_trunc_to_time, 208 "FROM_UNIXTIME": _from_unixtime, 209 "NOW": exp.CurrentTimestamp.from_arg_list, 210 "STRPOS": lambda args: exp.StrPosition( 211 this=seq_get(args, 0), 212 substr=seq_get(args, 1), 213 instance=seq_get(args, 2), 214 ), 215 "TO_UNIXTIME": exp.TimeToUnix.from_arg_list, 216 "APPROX_PERCENTILE": _approx_percentile, 217 "FROM_HEX": exp.Unhex.from_arg_list, 218 "TO_HEX": exp.Hex.from_arg_list, 219 "TO_UTF8": lambda args: exp.Encode( 220 this=seq_get(args, 0), charset=exp.Literal.string("utf-8") 221 ), 222 "FROM_UTF8": lambda args: exp.Decode( 223 this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8") 224 ), 225 } 226 FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy() 227 FUNCTION_PARSERS.pop("TRIM")
Parser consumes a list of tokens produced by the sqlglot.tokens.Tokenizer
and produces
a parsed syntax tree.
Arguments:
- error_level: the desired error level. Default: ErrorLevel.RAISE
- error_message_context: determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 50.
- index_offset: Index offset for arrays eg ARRAY[0] vs ARRAY[1] as the head of a list. Default: 0
- alias_post_tablesample: If the table alias comes after tablesample. Default: False
- max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3
- null_ordering: Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
Inherited Members
229 class Generator(generator.Generator): 230 STRUCT_DELIMITER = ("(", ")") 231 232 PROPERTIES_LOCATION = { 233 **generator.Generator.PROPERTIES_LOCATION, # type: ignore 234 exp.LocationProperty: exp.Properties.Location.UNSUPPORTED, 235 } 236 237 TYPE_MAPPING = { 238 **generator.Generator.TYPE_MAPPING, # type: ignore 239 exp.DataType.Type.INT: "INTEGER", 240 exp.DataType.Type.FLOAT: "REAL", 241 exp.DataType.Type.BINARY: "VARBINARY", 242 exp.DataType.Type.TEXT: "VARCHAR", 243 exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP", 244 exp.DataType.Type.STRUCT: "ROW", 245 } 246 247 TRANSFORMS = { 248 **generator.Generator.TRANSFORMS, # type: ignore 249 **transforms.UNALIAS_GROUP, # type: ignore 250 **transforms.ELIMINATE_QUALIFY, # type: ignore 251 exp.ApproxDistinct: _approx_distinct_sql, 252 exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]", 253 exp.ArrayConcat: rename_func("CONCAT"), 254 exp.ArrayContains: rename_func("CONTAINS"), 255 exp.ArraySize: rename_func("CARDINALITY"), 256 exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 257 exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 258 exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})", 259 exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 260 exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 261 exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 262 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 263 exp.DataType: _datatype_sql, 264 exp.DateAdd: lambda self, e: self.func( 265 "DATE_ADD", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this 266 ), 267 exp.DateDiff: lambda self, e: self.func( 268 "DATE_DIFF", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this 269 ), 270 exp.DateStrToDate: lambda self, e: f"CAST(DATE_PARSE({self.sql(e, 'this')}, {Presto.date_format}) AS DATE)", 271 exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.dateint_format}) AS INT)", 272 exp.Decode: _decode_sql, 273 exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.dateint_format}) AS DATE)", 274 exp.Encode: _encode_sql, 275 exp.GenerateSeries: _sequence_sql, 276 exp.Hex: rename_func("TO_HEX"), 277 exp.If: if_sql, 278 exp.ILike: no_ilike_sql, 279 exp.Initcap: _initcap_sql, 280 exp.Lateral: _explode_to_unnest_sql, 281 exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"), 282 exp.LogicalOr: rename_func("BOOL_OR"), 283 exp.LogicalAnd: rename_func("BOOL_AND"), 284 exp.Quantile: _quantile_sql, 285 exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"), 286 exp.SafeDivide: no_safe_divide_sql, 287 exp.Schema: _schema_sql, 288 exp.SortArray: _no_sort_array, 289 exp.StrPosition: rename_func("STRPOS"), 290 exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)", 291 exp.StrToTime: _str_to_time_sql, 292 exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))", 293 exp.StructExtract: struct_extract_sql, 294 exp.TableFormatProperty: lambda self, e: f"TABLE_FORMAT='{e.name.upper()}'", 295 exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'", 296 exp.TimestampTrunc: timestamptrunc_sql, 297 exp.TimeStrToDate: timestrtotime_sql, 298 exp.TimeStrToTime: timestrtotime_sql, 299 exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.time_format}))", 300 exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 301 exp.TimeToUnix: rename_func("TO_UNIXTIME"), 302 exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)", 303 exp.TsOrDsAdd: _ts_or_ds_add_sql, 304 exp.TsOrDsToDate: _ts_or_ds_to_date_sql, 305 exp.Unhex: rename_func("FROM_HEX"), 306 exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})", 307 exp.UnixToTime: rename_func("FROM_UNIXTIME"), 308 exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)", 309 exp.VariancePop: rename_func("VAR_POP"), 310 } 311 312 def transaction_sql(self, expression): 313 modes = expression.args.get("modes") 314 modes = f" {', '.join(modes)}" if modes else "" 315 return f"START TRANSACTION{modes}"
Generator interprets the given syntax tree and produces a SQL string as an output.
Arguments:
- time_mapping (dict): the dictionary of custom time mappings in which the key represents a python time format and the output the target time format
- time_trie (trie): a trie of the time_mapping keys
- pretty (bool): if set to True the returned string will be formatted. Default: False.
- quote_start (str): specifies which starting character to use to delimit quotes. Default: '.
- quote_end (str): specifies which ending character to use to delimit quotes. Default: '.
- identifier_start (str): specifies which starting character to use to delimit identifiers. Default: ".
- identifier_end (str): specifies which ending character to use to delimit identifiers. Default: ".
- identify (bool | str): 'always': always quote, 'safe': quote identifiers if they don't contain an upcase, True defaults to always.
- normalize (bool): if set to True all identifiers will lower cased
- string_escape (str): specifies a string escape character. Default: '.
- identifier_escape (str): specifies an identifier escape character. Default: ".
- pad (int): determines padding in a formatted string. Default: 2.
- indent (int): determines the size of indentation in a formatted string. Default: 4.
- unnest_column_only (bool): if true unnest table aliases are considered only as column aliases
- normalize_functions (str): normalize function names, "upper", "lower", or None Default: "upper"
- alias_post_tablesample (bool): if the table alias comes after tablesample Default: False
- unsupported_level (ErrorLevel): determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- null_ordering (str): Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
- max_unsupported (int): Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma (bool): if the the comma is leading or trailing in select statements Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether or not to preserve comments in the output SQL code. Default: True
Inherited Members
- sqlglot.generator.Generator
- Generator
- generate
- unsupported
- sep
- seg
- pad_comment
- maybe_comment
- wrap
- no_identify
- normalize_func
- indent
- sql
- uncache_sql
- cache_sql
- characterset_sql
- column_sql
- columndef_sql
- columnconstraint_sql
- autoincrementcolumnconstraint_sql
- compresscolumnconstraint_sql
- generatedasidentitycolumnconstraint_sql
- notnullcolumnconstraint_sql
- primarykeycolumnconstraint_sql
- uniquecolumnconstraint_sql
- create_sql
- describe_sql
- prepend_ctes
- with_sql
- cte_sql
- tablealias_sql
- bitstring_sql
- hexstring_sql
- datatype_sql
- directory_sql
- delete_sql
- drop_sql
- except_sql
- except_op
- fetch_sql
- filter_sql
- hint_sql
- index_sql
- identifier_sql
- national_sql
- partition_sql
- properties_sql
- root_properties
- properties
- with_properties
- locate_properties
- property_sql
- likeproperty_sql
- fallbackproperty_sql
- journalproperty_sql
- freespaceproperty_sql
- afterjournalproperty_sql
- checksumproperty_sql
- mergeblockratioproperty_sql
- datablocksizeproperty_sql
- blockcompressionproperty_sql
- isolatedloadingproperty_sql
- lockingproperty_sql
- withdataproperty_sql
- insert_sql
- intersect_sql
- intersect_op
- introducer_sql
- pseudotype_sql
- returning_sql
- rowformatdelimitedproperty_sql
- table_sql
- tablesample_sql
- pivot_sql
- tuple_sql
- update_sql
- values_sql
- var_sql
- into_sql
- from_sql
- group_sql
- having_sql
- join_sql
- lambda_sql
- lateral_sql
- limit_sql
- offset_sql
- setitem_sql
- set_sql
- lock_sql
- literal_sql
- loaddata_sql
- null_sql
- boolean_sql
- order_sql
- cluster_sql
- distribute_sql
- sort_sql
- ordered_sql
- matchrecognize_sql
- query_modifiers
- select_sql
- schema_sql
- star_sql
- structkwarg_sql
- parameter_sql
- sessionparameter_sql
- placeholder_sql
- subquery_sql
- qualify_sql
- union_sql
- union_op
- unnest_sql
- where_sql
- window_sql
- partition_by_sql
- window_spec_sql
- withingroup_sql
- between_sql
- bracket_sql
- all_sql
- any_sql
- exists_sql
- case_sql
- constraint_sql
- extract_sql
- trim_sql
- concat_sql
- check_sql
- foreignkey_sql
- primarykey_sql
- unique_sql
- if_sql
- in_sql
- in_unnest_op
- interval_sql
- return_sql
- reference_sql
- anonymous_sql
- paren_sql
- neg_sql
- not_sql
- alias_sql
- aliases_sql
- attimezone_sql
- add_sql
- and_sql
- connector_sql
- bitwiseand_sql
- bitwiseleftshift_sql
- bitwisenot_sql
- bitwiseor_sql
- bitwiserightshift_sql
- bitwisexor_sql
- cast_sql
- currentdate_sql
- collate_sql
- command_sql
- comment_sql
- commit_sql
- rollback_sql
- altercolumn_sql
- renametable_sql
- altertable_sql
- droppartition_sql
- addconstraint_sql
- distinct_sql
- ignorenulls_sql
- respectnulls_sql
- intdiv_sql
- dpipe_sql
- div_sql
- overlaps_sql
- distance_sql
- dot_sql
- eq_sql
- escape_sql
- glob_sql
- gt_sql
- gte_sql
- ilike_sql
- is_sql
- like_sql
- similarto_sql
- lt_sql
- lte_sql
- mod_sql
- mul_sql
- neq_sql
- nullsafeeq_sql
- nullsafeneq_sql
- or_sql
- slice_sql
- sub_sql
- trycast_sql
- use_sql
- binary
- function_fallback_sql
- func
- format_args
- text_width
- format_time
- expressions
- op_expressions
- naked_property
- set_operation
- tag_sql
- token_sql
- userdefinedfunction_sql
- joinhint_sql
- kwarg_sql
- when_sql
- merge_sql
- tochar_sql