sqlglot.dialects.postgres
1from __future__ import annotations 2 3from sqlglot import exp, generator, parser, tokens 4from sqlglot.dialects.dialect import ( 5 Dialect, 6 arrow_json_extract_scalar_sql, 7 arrow_json_extract_sql, 8 format_time_lambda, 9 no_paren_current_date_sql, 10 no_tablesample_sql, 11 no_trycast_sql, 12 rename_func, 13 str_position_sql, 14 trim_sql, 15) 16from sqlglot.helper import seq_get 17from sqlglot.tokens import TokenType 18from sqlglot.transforms import delegate, preprocess 19 20DATE_DIFF_FACTOR = { 21 "MICROSECOND": " * 1000000", 22 "MILLISECOND": " * 1000", 23 "SECOND": "", 24 "MINUTE": " / 60", 25 "HOUR": " / 3600", 26 "DAY": " / 86400", 27} 28 29 30def _date_add_sql(kind): 31 def func(self, expression): 32 from sqlglot.optimizer.simplify import simplify 33 34 this = self.sql(expression, "this") 35 unit = self.sql(expression, "unit") 36 expression = simplify(expression.args["expression"]) 37 38 if not isinstance(expression, exp.Literal): 39 self.unsupported("Cannot add non literal") 40 41 expression = expression.copy() 42 expression.args["is_string"] = True 43 return f"{this} {kind} {self.sql(exp.Interval(this=expression, unit=unit))}" 44 45 return func 46 47 48def _date_diff_sql(self, expression): 49 unit = expression.text("unit").upper() 50 factor = DATE_DIFF_FACTOR.get(unit) 51 52 end = f"CAST({expression.this} AS TIMESTAMP)" 53 start = f"CAST({expression.expression} AS TIMESTAMP)" 54 55 if factor is not None: 56 return f"CAST(EXTRACT(epoch FROM {end} - {start}){factor} AS BIGINT)" 57 58 age = f"AGE({end}, {start})" 59 60 if unit == "WEEK": 61 extract = f"EXTRACT(year FROM {age}) * 48 + EXTRACT(month FROM {age}) * 4 + EXTRACT(day FROM {age}) / 7" 62 elif unit == "MONTH": 63 extract = f"EXTRACT(year FROM {age}) * 12 + EXTRACT(month FROM {age})" 64 elif unit == "QUARTER": 65 extract = f"EXTRACT(year FROM {age}) * 4 + EXTRACT(month FROM {age}) / 3" 66 elif unit == "YEAR": 67 extract = f"EXTRACT(year FROM {age})" 68 else: 69 self.unsupported(f"Unsupported DATEDIFF unit {unit}") 70 71 return f"CAST({extract} AS BIGINT)" 72 73 74def _substring_sql(self, expression): 75 this = self.sql(expression, "this") 76 start = self.sql(expression, "start") 77 length = self.sql(expression, "length") 78 79 from_part = f" FROM {start}" if start else "" 80 for_part = f" FOR {length}" if length else "" 81 82 return f"SUBSTRING({this}{from_part}{for_part})" 83 84 85def _string_agg_sql(self, expression): 86 expression = expression.copy() 87 separator = expression.args.get("separator") or exp.Literal.string(",") 88 89 order = "" 90 this = expression.this 91 if isinstance(this, exp.Order): 92 if this.this: 93 this = this.this 94 this.pop() 95 order = self.sql(expression.this) # Order has a leading space 96 97 return f"STRING_AGG({self.format_args(this, separator)}{order})" 98 99 100def _datatype_sql(self, expression): 101 if expression.this == exp.DataType.Type.ARRAY: 102 return f"{self.expressions(expression, flat=True)}[]" 103 return self.datatype_sql(expression) 104 105 106def _auto_increment_to_serial(expression): 107 auto = expression.find(exp.AutoIncrementColumnConstraint) 108 109 if auto: 110 expression = expression.copy() 111 expression.args["constraints"].remove(auto.parent) 112 kind = expression.args["kind"] 113 114 if kind.this == exp.DataType.Type.INT: 115 kind.replace(exp.DataType(this=exp.DataType.Type.SERIAL)) 116 elif kind.this == exp.DataType.Type.SMALLINT: 117 kind.replace(exp.DataType(this=exp.DataType.Type.SMALLSERIAL)) 118 elif kind.this == exp.DataType.Type.BIGINT: 119 kind.replace(exp.DataType(this=exp.DataType.Type.BIGSERIAL)) 120 121 return expression 122 123 124def _serial_to_generated(expression): 125 kind = expression.args["kind"] 126 127 if kind.this == exp.DataType.Type.SERIAL: 128 data_type = exp.DataType(this=exp.DataType.Type.INT) 129 elif kind.this == exp.DataType.Type.SMALLSERIAL: 130 data_type = exp.DataType(this=exp.DataType.Type.SMALLINT) 131 elif kind.this == exp.DataType.Type.BIGSERIAL: 132 data_type = exp.DataType(this=exp.DataType.Type.BIGINT) 133 else: 134 data_type = None 135 136 if data_type: 137 expression = expression.copy() 138 expression.args["kind"].replace(data_type) 139 constraints = expression.args["constraints"] 140 generated = exp.ColumnConstraint(kind=exp.GeneratedAsIdentityColumnConstraint(this=False)) 141 notnull = exp.ColumnConstraint(kind=exp.NotNullColumnConstraint()) 142 if notnull not in constraints: 143 constraints.insert(0, notnull) 144 if generated not in constraints: 145 constraints.insert(0, generated) 146 147 return expression 148 149 150def _generate_series(args): 151 # The goal is to convert step values like '1 day' or INTERVAL '1 day' into INTERVAL '1' day 152 step = seq_get(args, 2) 153 154 if step is None: 155 # Postgres allows calls with just two arguments -- the "step" argument defaults to 1 156 return exp.GenerateSeries.from_arg_list(args) 157 158 if step.is_string: 159 args[2] = exp.to_interval(step.this) 160 elif isinstance(step, exp.Interval) and not step.args.get("unit"): 161 args[2] = exp.to_interval(step.this.this) 162 163 return exp.GenerateSeries.from_arg_list(args) 164 165 166def _to_timestamp(args): 167 # TO_TIMESTAMP accepts either a single double argument or (text, text) 168 if len(args) == 1: 169 # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TABLE 170 return exp.UnixToTime.from_arg_list(args) 171 # https://www.postgresql.org/docs/current/functions-formatting.html 172 return format_time_lambda(exp.StrToTime, "postgres")(args) 173 174 175class Postgres(Dialect): 176 null_ordering = "nulls_are_large" 177 time_format = "'YYYY-MM-DD HH24:MI:SS'" 178 time_mapping = { 179 "AM": "%p", 180 "PM": "%p", 181 "D": "%u", # 1-based day of week 182 "DD": "%d", # day of month 183 "DDD": "%j", # zero padded day of year 184 "FMDD": "%-d", # - is no leading zero for Python; same for FM in postgres 185 "FMDDD": "%-j", # day of year 186 "FMHH12": "%-I", # 9 187 "FMHH24": "%-H", # 9 188 "FMMI": "%-M", # Minute 189 "FMMM": "%-m", # 1 190 "FMSS": "%-S", # Second 191 "HH12": "%I", # 09 192 "HH24": "%H", # 09 193 "MI": "%M", # zero padded minute 194 "MM": "%m", # 01 195 "OF": "%z", # utc offset 196 "SS": "%S", # zero padded second 197 "TMDay": "%A", # TM is locale dependent 198 "TMDy": "%a", 199 "TMMon": "%b", # Sep 200 "TMMonth": "%B", # September 201 "TZ": "%Z", # uppercase timezone name 202 "US": "%f", # zero padded microsecond 203 "WW": "%U", # 1-based week of year 204 "YY": "%y", # 15 205 "YYYY": "%Y", # 2015 206 } 207 208 class Tokenizer(tokens.Tokenizer): 209 BIT_STRINGS = [("b'", "'"), ("B'", "'")] 210 HEX_STRINGS = [("x'", "'"), ("X'", "'")] 211 BYTE_STRINGS = [("e'", "'"), ("E'", "'")] 212 213 KEYWORDS = { 214 **tokens.Tokenizer.KEYWORDS, 215 "~~": TokenType.LIKE, 216 "~~*": TokenType.ILIKE, 217 "~*": TokenType.IRLIKE, 218 "~": TokenType.RLIKE, 219 "BEGIN": TokenType.COMMAND, 220 "BEGIN TRANSACTION": TokenType.BEGIN, 221 "BIGSERIAL": TokenType.BIGSERIAL, 222 "CHARACTER VARYING": TokenType.VARCHAR, 223 "COMMENT ON": TokenType.COMMAND, 224 "DECLARE": TokenType.COMMAND, 225 "DO": TokenType.COMMAND, 226 "GRANT": TokenType.COMMAND, 227 "HSTORE": TokenType.HSTORE, 228 "JSONB": TokenType.JSONB, 229 "REFRESH": TokenType.COMMAND, 230 "REINDEX": TokenType.COMMAND, 231 "RESET": TokenType.COMMAND, 232 "REVOKE": TokenType.COMMAND, 233 "SERIAL": TokenType.SERIAL, 234 "SMALLSERIAL": TokenType.SMALLSERIAL, 235 "TEMP": TokenType.TEMPORARY, 236 "UUID": TokenType.UUID, 237 "CSTRING": TokenType.PSEUDO_TYPE, 238 } 239 QUOTES = ["'", "$$"] 240 SINGLE_TOKENS = { 241 **tokens.Tokenizer.SINGLE_TOKENS, 242 "$": TokenType.PARAMETER, 243 } 244 245 class Parser(parser.Parser): 246 STRICT_CAST = False 247 248 FUNCTIONS = { 249 **parser.Parser.FUNCTIONS, # type: ignore 250 "NOW": exp.CurrentTimestamp.from_arg_list, 251 "TO_TIMESTAMP": _to_timestamp, 252 "TO_CHAR": format_time_lambda(exp.TimeToStr, "postgres"), 253 "GENERATE_SERIES": _generate_series, 254 } 255 256 BITWISE = { 257 **parser.Parser.BITWISE, # type: ignore 258 TokenType.HASH: exp.BitwiseXor, 259 } 260 261 FACTOR = { 262 **parser.Parser.FACTOR, # type: ignore 263 TokenType.CARET: exp.Pow, 264 } 265 266 class Generator(generator.Generator): 267 LOCKING_READS_SUPPORTED = True 268 269 TYPE_MAPPING = { 270 **generator.Generator.TYPE_MAPPING, # type: ignore 271 exp.DataType.Type.TINYINT: "SMALLINT", 272 exp.DataType.Type.FLOAT: "REAL", 273 exp.DataType.Type.DOUBLE: "DOUBLE PRECISION", 274 exp.DataType.Type.BINARY: "BYTEA", 275 exp.DataType.Type.VARBINARY: "BYTEA", 276 exp.DataType.Type.DATETIME: "TIMESTAMP", 277 } 278 279 TRANSFORMS = { 280 **generator.Generator.TRANSFORMS, # type: ignore 281 exp.BitwiseXor: lambda self, e: self.binary(e, "#"), 282 exp.ColumnDef: preprocess( 283 [ 284 _auto_increment_to_serial, 285 _serial_to_generated, 286 ], 287 delegate("columndef_sql"), 288 ), 289 exp.JSONExtract: arrow_json_extract_sql, 290 exp.JSONExtractScalar: arrow_json_extract_scalar_sql, 291 exp.JSONBExtract: lambda self, e: self.binary(e, "#>"), 292 exp.JSONBExtractScalar: lambda self, e: self.binary(e, "#>>"), 293 exp.JSONBContains: lambda self, e: self.binary(e, "?"), 294 exp.Pow: lambda self, e: self.binary(e, "^"), 295 exp.CurrentDate: no_paren_current_date_sql, 296 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 297 exp.DateAdd: _date_add_sql("+"), 298 exp.DateSub: _date_add_sql("-"), 299 exp.DateDiff: _date_diff_sql, 300 exp.LogicalOr: rename_func("BOOL_OR"), 301 exp.RegexpLike: lambda self, e: self.binary(e, "~"), 302 exp.RegexpILike: lambda self, e: self.binary(e, "~*"), 303 exp.StrPosition: str_position_sql, 304 exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})", 305 exp.Substring: _substring_sql, 306 exp.TimeStrToTime: lambda self, e: f"CAST({self.sql(e, 'this')} AS TIMESTAMP)", 307 exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})", 308 exp.TableSample: no_tablesample_sql, 309 exp.Trim: trim_sql, 310 exp.TryCast: no_trycast_sql, 311 exp.UnixToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')})", 312 exp.DataType: _datatype_sql, 313 exp.GroupConcat: _string_agg_sql, 314 exp.Array: lambda self, e: f"{self.normalize_func('ARRAY')}({self.sql(e.expressions[0])})" 315 if isinstance(seq_get(e.expressions, 0), exp.Select) 316 else f"{self.normalize_func('ARRAY')}[{self.expressions(e, flat=True)}]", 317 }
176class Postgres(Dialect): 177 null_ordering = "nulls_are_large" 178 time_format = "'YYYY-MM-DD HH24:MI:SS'" 179 time_mapping = { 180 "AM": "%p", 181 "PM": "%p", 182 "D": "%u", # 1-based day of week 183 "DD": "%d", # day of month 184 "DDD": "%j", # zero padded day of year 185 "FMDD": "%-d", # - is no leading zero for Python; same for FM in postgres 186 "FMDDD": "%-j", # day of year 187 "FMHH12": "%-I", # 9 188 "FMHH24": "%-H", # 9 189 "FMMI": "%-M", # Minute 190 "FMMM": "%-m", # 1 191 "FMSS": "%-S", # Second 192 "HH12": "%I", # 09 193 "HH24": "%H", # 09 194 "MI": "%M", # zero padded minute 195 "MM": "%m", # 01 196 "OF": "%z", # utc offset 197 "SS": "%S", # zero padded second 198 "TMDay": "%A", # TM is locale dependent 199 "TMDy": "%a", 200 "TMMon": "%b", # Sep 201 "TMMonth": "%B", # September 202 "TZ": "%Z", # uppercase timezone name 203 "US": "%f", # zero padded microsecond 204 "WW": "%U", # 1-based week of year 205 "YY": "%y", # 15 206 "YYYY": "%Y", # 2015 207 } 208 209 class Tokenizer(tokens.Tokenizer): 210 BIT_STRINGS = [("b'", "'"), ("B'", "'")] 211 HEX_STRINGS = [("x'", "'"), ("X'", "'")] 212 BYTE_STRINGS = [("e'", "'"), ("E'", "'")] 213 214 KEYWORDS = { 215 **tokens.Tokenizer.KEYWORDS, 216 "~~": TokenType.LIKE, 217 "~~*": TokenType.ILIKE, 218 "~*": TokenType.IRLIKE, 219 "~": TokenType.RLIKE, 220 "BEGIN": TokenType.COMMAND, 221 "BEGIN TRANSACTION": TokenType.BEGIN, 222 "BIGSERIAL": TokenType.BIGSERIAL, 223 "CHARACTER VARYING": TokenType.VARCHAR, 224 "COMMENT ON": TokenType.COMMAND, 225 "DECLARE": TokenType.COMMAND, 226 "DO": TokenType.COMMAND, 227 "GRANT": TokenType.COMMAND, 228 "HSTORE": TokenType.HSTORE, 229 "JSONB": TokenType.JSONB, 230 "REFRESH": TokenType.COMMAND, 231 "REINDEX": TokenType.COMMAND, 232 "RESET": TokenType.COMMAND, 233 "REVOKE": TokenType.COMMAND, 234 "SERIAL": TokenType.SERIAL, 235 "SMALLSERIAL": TokenType.SMALLSERIAL, 236 "TEMP": TokenType.TEMPORARY, 237 "UUID": TokenType.UUID, 238 "CSTRING": TokenType.PSEUDO_TYPE, 239 } 240 QUOTES = ["'", "$$"] 241 SINGLE_TOKENS = { 242 **tokens.Tokenizer.SINGLE_TOKENS, 243 "$": TokenType.PARAMETER, 244 } 245 246 class Parser(parser.Parser): 247 STRICT_CAST = False 248 249 FUNCTIONS = { 250 **parser.Parser.FUNCTIONS, # type: ignore 251 "NOW": exp.CurrentTimestamp.from_arg_list, 252 "TO_TIMESTAMP": _to_timestamp, 253 "TO_CHAR": format_time_lambda(exp.TimeToStr, "postgres"), 254 "GENERATE_SERIES": _generate_series, 255 } 256 257 BITWISE = { 258 **parser.Parser.BITWISE, # type: ignore 259 TokenType.HASH: exp.BitwiseXor, 260 } 261 262 FACTOR = { 263 **parser.Parser.FACTOR, # type: ignore 264 TokenType.CARET: exp.Pow, 265 } 266 267 class Generator(generator.Generator): 268 LOCKING_READS_SUPPORTED = True 269 270 TYPE_MAPPING = { 271 **generator.Generator.TYPE_MAPPING, # type: ignore 272 exp.DataType.Type.TINYINT: "SMALLINT", 273 exp.DataType.Type.FLOAT: "REAL", 274 exp.DataType.Type.DOUBLE: "DOUBLE PRECISION", 275 exp.DataType.Type.BINARY: "BYTEA", 276 exp.DataType.Type.VARBINARY: "BYTEA", 277 exp.DataType.Type.DATETIME: "TIMESTAMP", 278 } 279 280 TRANSFORMS = { 281 **generator.Generator.TRANSFORMS, # type: ignore 282 exp.BitwiseXor: lambda self, e: self.binary(e, "#"), 283 exp.ColumnDef: preprocess( 284 [ 285 _auto_increment_to_serial, 286 _serial_to_generated, 287 ], 288 delegate("columndef_sql"), 289 ), 290 exp.JSONExtract: arrow_json_extract_sql, 291 exp.JSONExtractScalar: arrow_json_extract_scalar_sql, 292 exp.JSONBExtract: lambda self, e: self.binary(e, "#>"), 293 exp.JSONBExtractScalar: lambda self, e: self.binary(e, "#>>"), 294 exp.JSONBContains: lambda self, e: self.binary(e, "?"), 295 exp.Pow: lambda self, e: self.binary(e, "^"), 296 exp.CurrentDate: no_paren_current_date_sql, 297 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 298 exp.DateAdd: _date_add_sql("+"), 299 exp.DateSub: _date_add_sql("-"), 300 exp.DateDiff: _date_diff_sql, 301 exp.LogicalOr: rename_func("BOOL_OR"), 302 exp.RegexpLike: lambda self, e: self.binary(e, "~"), 303 exp.RegexpILike: lambda self, e: self.binary(e, "~*"), 304 exp.StrPosition: str_position_sql, 305 exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})", 306 exp.Substring: _substring_sql, 307 exp.TimeStrToTime: lambda self, e: f"CAST({self.sql(e, 'this')} AS TIMESTAMP)", 308 exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})", 309 exp.TableSample: no_tablesample_sql, 310 exp.Trim: trim_sql, 311 exp.TryCast: no_trycast_sql, 312 exp.UnixToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')})", 313 exp.DataType: _datatype_sql, 314 exp.GroupConcat: _string_agg_sql, 315 exp.Array: lambda self, e: f"{self.normalize_func('ARRAY')}({self.sql(e.expressions[0])})" 316 if isinstance(seq_get(e.expressions, 0), exp.Select) 317 else f"{self.normalize_func('ARRAY')}[{self.expressions(e, flat=True)}]", 318 }
Inherited Members
209 class Tokenizer(tokens.Tokenizer): 210 BIT_STRINGS = [("b'", "'"), ("B'", "'")] 211 HEX_STRINGS = [("x'", "'"), ("X'", "'")] 212 BYTE_STRINGS = [("e'", "'"), ("E'", "'")] 213 214 KEYWORDS = { 215 **tokens.Tokenizer.KEYWORDS, 216 "~~": TokenType.LIKE, 217 "~~*": TokenType.ILIKE, 218 "~*": TokenType.IRLIKE, 219 "~": TokenType.RLIKE, 220 "BEGIN": TokenType.COMMAND, 221 "BEGIN TRANSACTION": TokenType.BEGIN, 222 "BIGSERIAL": TokenType.BIGSERIAL, 223 "CHARACTER VARYING": TokenType.VARCHAR, 224 "COMMENT ON": TokenType.COMMAND, 225 "DECLARE": TokenType.COMMAND, 226 "DO": TokenType.COMMAND, 227 "GRANT": TokenType.COMMAND, 228 "HSTORE": TokenType.HSTORE, 229 "JSONB": TokenType.JSONB, 230 "REFRESH": TokenType.COMMAND, 231 "REINDEX": TokenType.COMMAND, 232 "RESET": TokenType.COMMAND, 233 "REVOKE": TokenType.COMMAND, 234 "SERIAL": TokenType.SERIAL, 235 "SMALLSERIAL": TokenType.SMALLSERIAL, 236 "TEMP": TokenType.TEMPORARY, 237 "UUID": TokenType.UUID, 238 "CSTRING": TokenType.PSEUDO_TYPE, 239 } 240 QUOTES = ["'", "$$"] 241 SINGLE_TOKENS = { 242 **tokens.Tokenizer.SINGLE_TOKENS, 243 "$": TokenType.PARAMETER, 244 }
Inherited Members
246 class Parser(parser.Parser): 247 STRICT_CAST = False 248 249 FUNCTIONS = { 250 **parser.Parser.FUNCTIONS, # type: ignore 251 "NOW": exp.CurrentTimestamp.from_arg_list, 252 "TO_TIMESTAMP": _to_timestamp, 253 "TO_CHAR": format_time_lambda(exp.TimeToStr, "postgres"), 254 "GENERATE_SERIES": _generate_series, 255 } 256 257 BITWISE = { 258 **parser.Parser.BITWISE, # type: ignore 259 TokenType.HASH: exp.BitwiseXor, 260 } 261 262 FACTOR = { 263 **parser.Parser.FACTOR, # type: ignore 264 TokenType.CARET: exp.Pow, 265 }
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
267 class Generator(generator.Generator): 268 LOCKING_READS_SUPPORTED = True 269 270 TYPE_MAPPING = { 271 **generator.Generator.TYPE_MAPPING, # type: ignore 272 exp.DataType.Type.TINYINT: "SMALLINT", 273 exp.DataType.Type.FLOAT: "REAL", 274 exp.DataType.Type.DOUBLE: "DOUBLE PRECISION", 275 exp.DataType.Type.BINARY: "BYTEA", 276 exp.DataType.Type.VARBINARY: "BYTEA", 277 exp.DataType.Type.DATETIME: "TIMESTAMP", 278 } 279 280 TRANSFORMS = { 281 **generator.Generator.TRANSFORMS, # type: ignore 282 exp.BitwiseXor: lambda self, e: self.binary(e, "#"), 283 exp.ColumnDef: preprocess( 284 [ 285 _auto_increment_to_serial, 286 _serial_to_generated, 287 ], 288 delegate("columndef_sql"), 289 ), 290 exp.JSONExtract: arrow_json_extract_sql, 291 exp.JSONExtractScalar: arrow_json_extract_scalar_sql, 292 exp.JSONBExtract: lambda self, e: self.binary(e, "#>"), 293 exp.JSONBExtractScalar: lambda self, e: self.binary(e, "#>>"), 294 exp.JSONBContains: lambda self, e: self.binary(e, "?"), 295 exp.Pow: lambda self, e: self.binary(e, "^"), 296 exp.CurrentDate: no_paren_current_date_sql, 297 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 298 exp.DateAdd: _date_add_sql("+"), 299 exp.DateSub: _date_add_sql("-"), 300 exp.DateDiff: _date_diff_sql, 301 exp.LogicalOr: rename_func("BOOL_OR"), 302 exp.RegexpLike: lambda self, e: self.binary(e, "~"), 303 exp.RegexpILike: lambda self, e: self.binary(e, "~*"), 304 exp.StrPosition: str_position_sql, 305 exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})", 306 exp.Substring: _substring_sql, 307 exp.TimeStrToTime: lambda self, e: f"CAST({self.sql(e, 'this')} AS TIMESTAMP)", 308 exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})", 309 exp.TableSample: no_tablesample_sql, 310 exp.Trim: trim_sql, 311 exp.TryCast: no_trycast_sql, 312 exp.UnixToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')})", 313 exp.DataType: _datatype_sql, 314 exp.GroupConcat: _string_agg_sql, 315 exp.Array: lambda self, e: f"{self.normalize_func('ARRAY')}({self.sql(e.expressions[0])})" 316 if isinstance(seq_get(e.expressions, 0), exp.Select) 317 else f"{self.normalize_func('ARRAY')}[{self.expressions(e, flat=True)}]", 318 }
Generator interprets the given syntax tree and produces a SQL string as an output.
Arguments:
- time_mapping (dict): the dictionary of custom time mappings in which the key represents a python time format and the output the target time format
- time_trie (trie): a trie of the time_mapping keys
- pretty (bool): if set to True the returned string will be formatted. Default: False.
- quote_start (str): specifies which starting character to use to delimit quotes. Default: '.
- quote_end (str): specifies which ending character to use to delimit quotes. Default: '.
- identifier_start (str): specifies which starting character to use to delimit identifiers. Default: ".
- identifier_end (str): specifies which ending character to use to delimit identifiers. Default: ".
- identify (bool): if set to True all identifiers will be delimited by the corresponding character.
- normalize (bool): if set to True all identifiers will lower cased
- string_escape (str): specifies a string escape character. Default: '.
- identifier_escape (str): specifies an identifier escape character. Default: ".
- pad (int): determines padding in a formatted string. Default: 2.
- indent (int): determines the size of indentation in a formatted string. Default: 4.
- unnest_column_only (bool): if true unnest table aliases are considered only as column aliases
- normalize_functions (str): normalize function names, "upper", "lower", or None Default: "upper"
- alias_post_tablesample (bool): if the table alias comes after tablesample Default: False
- unsupported_level (ErrorLevel): determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- null_ordering (str): Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
- max_unsupported (int): Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma (bool): if the the comma is leading or trailing in select statements Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether or not to preserve comments in the output SQL code. Default: True
Inherited Members
- sqlglot.generator.Generator
- Generator
- generate
- unsupported
- sep
- seg
- pad_comment
- maybe_comment
- wrap
- no_identify
- normalize_func
- indent
- sql
- uncache_sql
- cache_sql
- characterset_sql
- column_sql
- columndef_sql
- columnconstraint_sql
- autoincrementcolumnconstraint_sql
- checkcolumnconstraint_sql
- commentcolumnconstraint_sql
- collatecolumnconstraint_sql
- encodecolumnconstraint_sql
- defaultcolumnconstraint_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
- insert_sql
- intersect_sql
- intersect_op
- introducer_sql
- pseudotype_sql
- rowformatdelimitedproperty_sql
- table_sql
- tablesample_sql
- pivot_sql
- tuple_sql
- update_sql
- values_sql
- var_sql
- into_sql
- from_sql
- group_sql
- having_sql
- join_sql
- lambda_sql
- lateral_sql
- limit_sql
- offset_sql
- lock_sql
- literal_sql
- loaddata_sql
- null_sql
- boolean_sql
- order_sql
- cluster_sql
- distribute_sql
- sort_sql
- ordered_sql
- matchrecognize_sql
- query_modifiers
- select_sql
- schema_sql
- star_sql
- structkwarg_sql
- parameter_sql
- sessionparameter_sql
- placeholder_sql
- subquery_sql
- qualify_sql
- union_sql
- union_op
- unnest_sql
- where_sql
- window_sql
- partition_by_sql
- window_spec_sql
- withingroup_sql
- between_sql
- bracket_sql
- all_sql
- any_sql
- exists_sql
- case_sql
- constraint_sql
- extract_sql
- trim_sql
- concat_sql
- check_sql
- foreignkey_sql
- primarykey_sql
- unique_sql
- if_sql
- in_sql
- in_unnest_op
- interval_sql
- return_sql
- reference_sql
- anonymous_sql
- paren_sql
- neg_sql
- not_sql
- alias_sql
- aliases_sql
- attimezone_sql
- add_sql
- and_sql
- connector_sql
- bitwiseand_sql
- bitwiseleftshift_sql
- bitwisenot_sql
- bitwiseor_sql
- bitwiserightshift_sql
- bitwisexor_sql
- cast_sql
- currentdate_sql
- collate_sql
- command_sql
- transaction_sql
- commit_sql
- rollback_sql
- altercolumn_sql
- renametable_sql
- altertable_sql
- droppartition_sql
- addconstraint_sql
- distinct_sql
- ignorenulls_sql
- respectnulls_sql
- intdiv_sql
- dpipe_sql
- div_sql
- distance_sql
- dot_sql
- eq_sql
- escape_sql
- glob_sql
- gt_sql
- gte_sql
- ilike_sql
- is_sql
- like_sql
- similarto_sql
- lt_sql
- lte_sql
- mod_sql
- mul_sql
- neq_sql
- nullsafeeq_sql
- nullsafeneq_sql
- or_sql
- slice_sql
- sub_sql
- trycast_sql
- use_sql
- binary
- function_fallback_sql
- format_args
- text_width
- format_time
- expressions
- op_expressions
- naked_property
- set_operation
- tag_sql
- token_sql
- userdefinedfunction_sql
- userdefinedfunctionkwarg_sql
- joinhint_sql
- kwarg_sql
- when_sql
- merge_sql