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 min_or_least, 10 no_paren_current_date_sql, 11 no_tablesample_sql, 12 no_trycast_sql, 13 rename_func, 14 str_position_sql, 15 timestamptrunc_sql, 16 trim_sql, 17) 18from sqlglot.helper import seq_get 19from sqlglot.parser import binary_range_parser 20from sqlglot.tokens import TokenType 21from sqlglot.transforms import delegate, preprocess 22 23DATE_DIFF_FACTOR = { 24 "MICROSECOND": " * 1000000", 25 "MILLISECOND": " * 1000", 26 "SECOND": "", 27 "MINUTE": " / 60", 28 "HOUR": " / 3600", 29 "DAY": " / 86400", 30} 31 32 33def _date_add_sql(kind): 34 def func(self, expression): 35 from sqlglot.optimizer.simplify import simplify 36 37 this = self.sql(expression, "this") 38 unit = expression.args.get("unit") 39 expression = simplify(expression.args["expression"]) 40 41 if not isinstance(expression, exp.Literal): 42 self.unsupported("Cannot add non literal") 43 44 expression = expression.copy() 45 expression.args["is_string"] = True 46 return f"{this} {kind} {self.sql(exp.Interval(this=expression, unit=unit))}" 47 48 return func 49 50 51def _date_diff_sql(self, expression): 52 unit = expression.text("unit").upper() 53 factor = DATE_DIFF_FACTOR.get(unit) 54 55 end = f"CAST({expression.this} AS TIMESTAMP)" 56 start = f"CAST({expression.expression} AS TIMESTAMP)" 57 58 if factor is not None: 59 return f"CAST(EXTRACT(epoch FROM {end} - {start}){factor} AS BIGINT)" 60 61 age = f"AGE({end}, {start})" 62 63 if unit == "WEEK": 64 unit = f"EXTRACT(year FROM {age}) * 48 + EXTRACT(month FROM {age}) * 4 + EXTRACT(day FROM {age}) / 7" 65 elif unit == "MONTH": 66 unit = f"EXTRACT(year FROM {age}) * 12 + EXTRACT(month FROM {age})" 67 elif unit == "QUARTER": 68 unit = f"EXTRACT(year FROM {age}) * 4 + EXTRACT(month FROM {age}) / 3" 69 elif unit == "YEAR": 70 unit = f"EXTRACT(year FROM {age})" 71 else: 72 unit = age 73 74 return f"CAST({unit} AS BIGINT)" 75 76 77def _substring_sql(self, expression): 78 this = self.sql(expression, "this") 79 start = self.sql(expression, "start") 80 length = self.sql(expression, "length") 81 82 from_part = f" FROM {start}" if start else "" 83 for_part = f" FOR {length}" if length else "" 84 85 return f"SUBSTRING({this}{from_part}{for_part})" 86 87 88def _string_agg_sql(self, expression): 89 expression = expression.copy() 90 separator = expression.args.get("separator") or exp.Literal.string(",") 91 92 order = "" 93 this = expression.this 94 if isinstance(this, exp.Order): 95 if this.this: 96 this = this.this.pop() 97 order = self.sql(expression.this) # Order has a leading space 98 99 return f"STRING_AGG({self.format_args(this, separator)}{order})" 100 101 102def _datatype_sql(self, expression): 103 if expression.this == exp.DataType.Type.ARRAY: 104 return f"{self.expressions(expression, flat=True)}[]" 105 return self.datatype_sql(expression) 106 107 108def _auto_increment_to_serial(expression): 109 auto = expression.find(exp.AutoIncrementColumnConstraint) 110 111 if auto: 112 expression = expression.copy() 113 expression.args["constraints"].remove(auto.parent) 114 kind = expression.args["kind"] 115 116 if kind.this == exp.DataType.Type.INT: 117 kind.replace(exp.DataType(this=exp.DataType.Type.SERIAL)) 118 elif kind.this == exp.DataType.Type.SMALLINT: 119 kind.replace(exp.DataType(this=exp.DataType.Type.SMALLSERIAL)) 120 elif kind.this == exp.DataType.Type.BIGINT: 121 kind.replace(exp.DataType(this=exp.DataType.Type.BIGSERIAL)) 122 123 return expression 124 125 126def _serial_to_generated(expression): 127 kind = expression.args["kind"] 128 129 if kind.this == exp.DataType.Type.SERIAL: 130 data_type = exp.DataType(this=exp.DataType.Type.INT) 131 elif kind.this == exp.DataType.Type.SMALLSERIAL: 132 data_type = exp.DataType(this=exp.DataType.Type.SMALLINT) 133 elif kind.this == exp.DataType.Type.BIGSERIAL: 134 data_type = exp.DataType(this=exp.DataType.Type.BIGINT) 135 else: 136 data_type = None 137 138 if data_type: 139 expression = expression.copy() 140 expression.args["kind"].replace(data_type) 141 constraints = expression.args["constraints"] 142 generated = exp.ColumnConstraint(kind=exp.GeneratedAsIdentityColumnConstraint(this=False)) 143 notnull = exp.ColumnConstraint(kind=exp.NotNullColumnConstraint()) 144 if notnull not in constraints: 145 constraints.insert(0, notnull) 146 if generated not in constraints: 147 constraints.insert(0, generated) 148 149 return expression 150 151 152def _generate_series(args): 153 # The goal is to convert step values like '1 day' or INTERVAL '1 day' into INTERVAL '1' day 154 step = seq_get(args, 2) 155 156 if step is None: 157 # Postgres allows calls with just two arguments -- the "step" argument defaults to 1 158 return exp.GenerateSeries.from_arg_list(args) 159 160 if step.is_string: 161 args[2] = exp.to_interval(step.this) 162 elif isinstance(step, exp.Interval) and not step.args.get("unit"): 163 args[2] = exp.to_interval(step.this.this) 164 165 return exp.GenerateSeries.from_arg_list(args) 166 167 168def _to_timestamp(args): 169 # TO_TIMESTAMP accepts either a single double argument or (text, text) 170 if len(args) == 1: 171 # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TABLE 172 return exp.UnixToTime.from_arg_list(args) 173 # https://www.postgresql.org/docs/current/functions-formatting.html 174 return format_time_lambda(exp.StrToTime, "postgres")(args) 175 176 177class Postgres(Dialect): 178 null_ordering = "nulls_are_large" 179 time_format = "'YYYY-MM-DD HH24:MI:SS'" 180 time_mapping = { 181 "AM": "%p", 182 "PM": "%p", 183 "D": "%u", # 1-based day of week 184 "DD": "%d", # day of month 185 "DDD": "%j", # zero padded day of year 186 "FMDD": "%-d", # - is no leading zero for Python; same for FM in postgres 187 "FMDDD": "%-j", # day of year 188 "FMHH12": "%-I", # 9 189 "FMHH24": "%-H", # 9 190 "FMMI": "%-M", # Minute 191 "FMMM": "%-m", # 1 192 "FMSS": "%-S", # Second 193 "HH12": "%I", # 09 194 "HH24": "%H", # 09 195 "MI": "%M", # zero padded minute 196 "MM": "%m", # 01 197 "OF": "%z", # utc offset 198 "SS": "%S", # zero padded second 199 "TMDay": "%A", # TM is locale dependent 200 "TMDy": "%a", 201 "TMMon": "%b", # Sep 202 "TMMonth": "%B", # September 203 "TZ": "%Z", # uppercase timezone name 204 "US": "%f", # zero padded microsecond 205 "WW": "%U", # 1-based week of year 206 "YY": "%y", # 15 207 "YYYY": "%Y", # 2015 208 } 209 210 class Tokenizer(tokens.Tokenizer): 211 QUOTES = ["'", "$$"] 212 213 BIT_STRINGS = [("b'", "'"), ("B'", "'")] 214 HEX_STRINGS = [("x'", "'"), ("X'", "'")] 215 BYTE_STRINGS = [("e'", "'"), ("E'", "'")] 216 217 KEYWORDS = { 218 **tokens.Tokenizer.KEYWORDS, 219 "~~": TokenType.LIKE, 220 "~~*": TokenType.ILIKE, 221 "~*": TokenType.IRLIKE, 222 "~": TokenType.RLIKE, 223 "@>": TokenType.AT_GT, 224 "<@": TokenType.LT_AT, 225 "BEGIN": TokenType.COMMAND, 226 "BEGIN TRANSACTION": TokenType.BEGIN, 227 "BIGSERIAL": TokenType.BIGSERIAL, 228 "CHARACTER VARYING": TokenType.VARCHAR, 229 "DECLARE": TokenType.COMMAND, 230 "DO": TokenType.COMMAND, 231 "HSTORE": TokenType.HSTORE, 232 "JSONB": TokenType.JSONB, 233 "REFRESH": TokenType.COMMAND, 234 "REINDEX": TokenType.COMMAND, 235 "RESET": TokenType.COMMAND, 236 "RETURNING": TokenType.RETURNING, 237 "REVOKE": TokenType.COMMAND, 238 "SERIAL": TokenType.SERIAL, 239 "SMALLSERIAL": TokenType.SMALLSERIAL, 240 "TEMP": TokenType.TEMPORARY, 241 "UUID": TokenType.UUID, 242 "CSTRING": TokenType.PSEUDO_TYPE, 243 } 244 245 SINGLE_TOKENS = { 246 **tokens.Tokenizer.SINGLE_TOKENS, 247 "$": TokenType.PARAMETER, 248 } 249 250 class Parser(parser.Parser): 251 STRICT_CAST = False 252 253 FUNCTIONS = { 254 **parser.Parser.FUNCTIONS, # type: ignore 255 "NOW": exp.CurrentTimestamp.from_arg_list, 256 "TO_TIMESTAMP": _to_timestamp, 257 "TO_CHAR": format_time_lambda(exp.TimeToStr, "postgres"), 258 "GENERATE_SERIES": _generate_series, 259 "DATE_TRUNC": lambda args: exp.TimestampTrunc( 260 this=seq_get(args, 1), unit=seq_get(args, 0) 261 ), 262 } 263 264 BITWISE = { 265 **parser.Parser.BITWISE, # type: ignore 266 TokenType.HASH: exp.BitwiseXor, 267 } 268 269 FACTOR = { 270 **parser.Parser.FACTOR, 271 TokenType.CARET: exp.Pow, 272 } 273 274 RANGE_PARSERS = { 275 **parser.Parser.RANGE_PARSERS, # type: ignore 276 TokenType.DAMP: binary_range_parser(exp.ArrayOverlaps), 277 TokenType.AT_GT: binary_range_parser(exp.ArrayContains), 278 TokenType.LT_AT: binary_range_parser(exp.ArrayContained), 279 } 280 281 class Generator(generator.Generator): 282 LOCKING_READS_SUPPORTED = True 283 PARAMETER_TOKEN = "$" 284 285 TYPE_MAPPING = { 286 **generator.Generator.TYPE_MAPPING, # type: ignore 287 exp.DataType.Type.TINYINT: "SMALLINT", 288 exp.DataType.Type.FLOAT: "REAL", 289 exp.DataType.Type.DOUBLE: "DOUBLE PRECISION", 290 exp.DataType.Type.BINARY: "BYTEA", 291 exp.DataType.Type.VARBINARY: "BYTEA", 292 exp.DataType.Type.DATETIME: "TIMESTAMP", 293 } 294 295 TRANSFORMS = { 296 **generator.Generator.TRANSFORMS, # type: ignore 297 exp.BitwiseXor: lambda self, e: self.binary(e, "#"), 298 exp.ColumnDef: preprocess( 299 [ 300 _auto_increment_to_serial, 301 _serial_to_generated, 302 ], 303 delegate("columndef_sql"), 304 ), 305 exp.JSONExtract: arrow_json_extract_sql, 306 exp.JSONExtractScalar: arrow_json_extract_scalar_sql, 307 exp.JSONBExtract: lambda self, e: self.binary(e, "#>"), 308 exp.JSONBExtractScalar: lambda self, e: self.binary(e, "#>>"), 309 exp.JSONBContains: lambda self, e: self.binary(e, "?"), 310 exp.Pow: lambda self, e: self.binary(e, "^"), 311 exp.CurrentDate: no_paren_current_date_sql, 312 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 313 exp.DateAdd: _date_add_sql("+"), 314 exp.DateSub: _date_add_sql("-"), 315 exp.DateDiff: _date_diff_sql, 316 exp.LogicalOr: rename_func("BOOL_OR"), 317 exp.LogicalAnd: rename_func("BOOL_AND"), 318 exp.Min: min_or_least, 319 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 320 exp.ArrayContains: lambda self, e: self.binary(e, "@>"), 321 exp.ArrayContained: lambda self, e: self.binary(e, "<@"), 322 exp.RegexpLike: lambda self, e: self.binary(e, "~"), 323 exp.RegexpILike: lambda self, e: self.binary(e, "~*"), 324 exp.StrPosition: str_position_sql, 325 exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})", 326 exp.Substring: _substring_sql, 327 exp.TimestampTrunc: timestamptrunc_sql, 328 exp.TimeStrToTime: lambda self, e: f"CAST({self.sql(e, 'this')} AS TIMESTAMP)", 329 exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})", 330 exp.TableSample: no_tablesample_sql, 331 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 332 exp.Trim: trim_sql, 333 exp.TryCast: no_trycast_sql, 334 exp.UnixToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')})", 335 exp.DataType: _datatype_sql, 336 exp.GroupConcat: _string_agg_sql, 337 exp.Array: lambda self, e: f"{self.normalize_func('ARRAY')}({self.sql(e.expressions[0])})" 338 if isinstance(seq_get(e.expressions, 0), exp.Select) 339 else f"{self.normalize_func('ARRAY')}[{self.expressions(e, flat=True)}]", 340 } 341 342 PROPERTIES_LOCATION = { 343 **generator.Generator.PROPERTIES_LOCATION, # type: ignore 344 exp.TransientProperty: exp.Properties.Location.UNSUPPORTED, 345 }
178class Postgres(Dialect): 179 null_ordering = "nulls_are_large" 180 time_format = "'YYYY-MM-DD HH24:MI:SS'" 181 time_mapping = { 182 "AM": "%p", 183 "PM": "%p", 184 "D": "%u", # 1-based day of week 185 "DD": "%d", # day of month 186 "DDD": "%j", # zero padded day of year 187 "FMDD": "%-d", # - is no leading zero for Python; same for FM in postgres 188 "FMDDD": "%-j", # day of year 189 "FMHH12": "%-I", # 9 190 "FMHH24": "%-H", # 9 191 "FMMI": "%-M", # Minute 192 "FMMM": "%-m", # 1 193 "FMSS": "%-S", # Second 194 "HH12": "%I", # 09 195 "HH24": "%H", # 09 196 "MI": "%M", # zero padded minute 197 "MM": "%m", # 01 198 "OF": "%z", # utc offset 199 "SS": "%S", # zero padded second 200 "TMDay": "%A", # TM is locale dependent 201 "TMDy": "%a", 202 "TMMon": "%b", # Sep 203 "TMMonth": "%B", # September 204 "TZ": "%Z", # uppercase timezone name 205 "US": "%f", # zero padded microsecond 206 "WW": "%U", # 1-based week of year 207 "YY": "%y", # 15 208 "YYYY": "%Y", # 2015 209 } 210 211 class Tokenizer(tokens.Tokenizer): 212 QUOTES = ["'", "$$"] 213 214 BIT_STRINGS = [("b'", "'"), ("B'", "'")] 215 HEX_STRINGS = [("x'", "'"), ("X'", "'")] 216 BYTE_STRINGS = [("e'", "'"), ("E'", "'")] 217 218 KEYWORDS = { 219 **tokens.Tokenizer.KEYWORDS, 220 "~~": TokenType.LIKE, 221 "~~*": TokenType.ILIKE, 222 "~*": TokenType.IRLIKE, 223 "~": TokenType.RLIKE, 224 "@>": TokenType.AT_GT, 225 "<@": TokenType.LT_AT, 226 "BEGIN": TokenType.COMMAND, 227 "BEGIN TRANSACTION": TokenType.BEGIN, 228 "BIGSERIAL": TokenType.BIGSERIAL, 229 "CHARACTER VARYING": TokenType.VARCHAR, 230 "DECLARE": TokenType.COMMAND, 231 "DO": TokenType.COMMAND, 232 "HSTORE": TokenType.HSTORE, 233 "JSONB": TokenType.JSONB, 234 "REFRESH": TokenType.COMMAND, 235 "REINDEX": TokenType.COMMAND, 236 "RESET": TokenType.COMMAND, 237 "RETURNING": TokenType.RETURNING, 238 "REVOKE": TokenType.COMMAND, 239 "SERIAL": TokenType.SERIAL, 240 "SMALLSERIAL": TokenType.SMALLSERIAL, 241 "TEMP": TokenType.TEMPORARY, 242 "UUID": TokenType.UUID, 243 "CSTRING": TokenType.PSEUDO_TYPE, 244 } 245 246 SINGLE_TOKENS = { 247 **tokens.Tokenizer.SINGLE_TOKENS, 248 "$": TokenType.PARAMETER, 249 } 250 251 class Parser(parser.Parser): 252 STRICT_CAST = False 253 254 FUNCTIONS = { 255 **parser.Parser.FUNCTIONS, # type: ignore 256 "NOW": exp.CurrentTimestamp.from_arg_list, 257 "TO_TIMESTAMP": _to_timestamp, 258 "TO_CHAR": format_time_lambda(exp.TimeToStr, "postgres"), 259 "GENERATE_SERIES": _generate_series, 260 "DATE_TRUNC": lambda args: exp.TimestampTrunc( 261 this=seq_get(args, 1), unit=seq_get(args, 0) 262 ), 263 } 264 265 BITWISE = { 266 **parser.Parser.BITWISE, # type: ignore 267 TokenType.HASH: exp.BitwiseXor, 268 } 269 270 FACTOR = { 271 **parser.Parser.FACTOR, 272 TokenType.CARET: exp.Pow, 273 } 274 275 RANGE_PARSERS = { 276 **parser.Parser.RANGE_PARSERS, # type: ignore 277 TokenType.DAMP: binary_range_parser(exp.ArrayOverlaps), 278 TokenType.AT_GT: binary_range_parser(exp.ArrayContains), 279 TokenType.LT_AT: binary_range_parser(exp.ArrayContained), 280 } 281 282 class Generator(generator.Generator): 283 LOCKING_READS_SUPPORTED = True 284 PARAMETER_TOKEN = "$" 285 286 TYPE_MAPPING = { 287 **generator.Generator.TYPE_MAPPING, # type: ignore 288 exp.DataType.Type.TINYINT: "SMALLINT", 289 exp.DataType.Type.FLOAT: "REAL", 290 exp.DataType.Type.DOUBLE: "DOUBLE PRECISION", 291 exp.DataType.Type.BINARY: "BYTEA", 292 exp.DataType.Type.VARBINARY: "BYTEA", 293 exp.DataType.Type.DATETIME: "TIMESTAMP", 294 } 295 296 TRANSFORMS = { 297 **generator.Generator.TRANSFORMS, # type: ignore 298 exp.BitwiseXor: lambda self, e: self.binary(e, "#"), 299 exp.ColumnDef: preprocess( 300 [ 301 _auto_increment_to_serial, 302 _serial_to_generated, 303 ], 304 delegate("columndef_sql"), 305 ), 306 exp.JSONExtract: arrow_json_extract_sql, 307 exp.JSONExtractScalar: arrow_json_extract_scalar_sql, 308 exp.JSONBExtract: lambda self, e: self.binary(e, "#>"), 309 exp.JSONBExtractScalar: lambda self, e: self.binary(e, "#>>"), 310 exp.JSONBContains: lambda self, e: self.binary(e, "?"), 311 exp.Pow: lambda self, e: self.binary(e, "^"), 312 exp.CurrentDate: no_paren_current_date_sql, 313 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 314 exp.DateAdd: _date_add_sql("+"), 315 exp.DateSub: _date_add_sql("-"), 316 exp.DateDiff: _date_diff_sql, 317 exp.LogicalOr: rename_func("BOOL_OR"), 318 exp.LogicalAnd: rename_func("BOOL_AND"), 319 exp.Min: min_or_least, 320 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 321 exp.ArrayContains: lambda self, e: self.binary(e, "@>"), 322 exp.ArrayContained: lambda self, e: self.binary(e, "<@"), 323 exp.RegexpLike: lambda self, e: self.binary(e, "~"), 324 exp.RegexpILike: lambda self, e: self.binary(e, "~*"), 325 exp.StrPosition: str_position_sql, 326 exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})", 327 exp.Substring: _substring_sql, 328 exp.TimestampTrunc: timestamptrunc_sql, 329 exp.TimeStrToTime: lambda self, e: f"CAST({self.sql(e, 'this')} AS TIMESTAMP)", 330 exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})", 331 exp.TableSample: no_tablesample_sql, 332 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 333 exp.Trim: trim_sql, 334 exp.TryCast: no_trycast_sql, 335 exp.UnixToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')})", 336 exp.DataType: _datatype_sql, 337 exp.GroupConcat: _string_agg_sql, 338 exp.Array: lambda self, e: f"{self.normalize_func('ARRAY')}({self.sql(e.expressions[0])})" 339 if isinstance(seq_get(e.expressions, 0), exp.Select) 340 else f"{self.normalize_func('ARRAY')}[{self.expressions(e, flat=True)}]", 341 } 342 343 PROPERTIES_LOCATION = { 344 **generator.Generator.PROPERTIES_LOCATION, # type: ignore 345 exp.TransientProperty: exp.Properties.Location.UNSUPPORTED, 346 }
211 class Tokenizer(tokens.Tokenizer): 212 QUOTES = ["'", "$$"] 213 214 BIT_STRINGS = [("b'", "'"), ("B'", "'")] 215 HEX_STRINGS = [("x'", "'"), ("X'", "'")] 216 BYTE_STRINGS = [("e'", "'"), ("E'", "'")] 217 218 KEYWORDS = { 219 **tokens.Tokenizer.KEYWORDS, 220 "~~": TokenType.LIKE, 221 "~~*": TokenType.ILIKE, 222 "~*": TokenType.IRLIKE, 223 "~": TokenType.RLIKE, 224 "@>": TokenType.AT_GT, 225 "<@": TokenType.LT_AT, 226 "BEGIN": TokenType.COMMAND, 227 "BEGIN TRANSACTION": TokenType.BEGIN, 228 "BIGSERIAL": TokenType.BIGSERIAL, 229 "CHARACTER VARYING": TokenType.VARCHAR, 230 "DECLARE": TokenType.COMMAND, 231 "DO": TokenType.COMMAND, 232 "HSTORE": TokenType.HSTORE, 233 "JSONB": TokenType.JSONB, 234 "REFRESH": TokenType.COMMAND, 235 "REINDEX": TokenType.COMMAND, 236 "RESET": TokenType.COMMAND, 237 "RETURNING": TokenType.RETURNING, 238 "REVOKE": TokenType.COMMAND, 239 "SERIAL": TokenType.SERIAL, 240 "SMALLSERIAL": TokenType.SMALLSERIAL, 241 "TEMP": TokenType.TEMPORARY, 242 "UUID": TokenType.UUID, 243 "CSTRING": TokenType.PSEUDO_TYPE, 244 } 245 246 SINGLE_TOKENS = { 247 **tokens.Tokenizer.SINGLE_TOKENS, 248 "$": TokenType.PARAMETER, 249 }
Inherited Members
251 class Parser(parser.Parser): 252 STRICT_CAST = False 253 254 FUNCTIONS = { 255 **parser.Parser.FUNCTIONS, # type: ignore 256 "NOW": exp.CurrentTimestamp.from_arg_list, 257 "TO_TIMESTAMP": _to_timestamp, 258 "TO_CHAR": format_time_lambda(exp.TimeToStr, "postgres"), 259 "GENERATE_SERIES": _generate_series, 260 "DATE_TRUNC": lambda args: exp.TimestampTrunc( 261 this=seq_get(args, 1), unit=seq_get(args, 0) 262 ), 263 } 264 265 BITWISE = { 266 **parser.Parser.BITWISE, # type: ignore 267 TokenType.HASH: exp.BitwiseXor, 268 } 269 270 FACTOR = { 271 **parser.Parser.FACTOR, 272 TokenType.CARET: exp.Pow, 273 } 274 275 RANGE_PARSERS = { 276 **parser.Parser.RANGE_PARSERS, # type: ignore 277 TokenType.DAMP: binary_range_parser(exp.ArrayOverlaps), 278 TokenType.AT_GT: binary_range_parser(exp.ArrayContains), 279 TokenType.LT_AT: binary_range_parser(exp.ArrayContained), 280 }
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
282 class Generator(generator.Generator): 283 LOCKING_READS_SUPPORTED = True 284 PARAMETER_TOKEN = "$" 285 286 TYPE_MAPPING = { 287 **generator.Generator.TYPE_MAPPING, # type: ignore 288 exp.DataType.Type.TINYINT: "SMALLINT", 289 exp.DataType.Type.FLOAT: "REAL", 290 exp.DataType.Type.DOUBLE: "DOUBLE PRECISION", 291 exp.DataType.Type.BINARY: "BYTEA", 292 exp.DataType.Type.VARBINARY: "BYTEA", 293 exp.DataType.Type.DATETIME: "TIMESTAMP", 294 } 295 296 TRANSFORMS = { 297 **generator.Generator.TRANSFORMS, # type: ignore 298 exp.BitwiseXor: lambda self, e: self.binary(e, "#"), 299 exp.ColumnDef: preprocess( 300 [ 301 _auto_increment_to_serial, 302 _serial_to_generated, 303 ], 304 delegate("columndef_sql"), 305 ), 306 exp.JSONExtract: arrow_json_extract_sql, 307 exp.JSONExtractScalar: arrow_json_extract_scalar_sql, 308 exp.JSONBExtract: lambda self, e: self.binary(e, "#>"), 309 exp.JSONBExtractScalar: lambda self, e: self.binary(e, "#>>"), 310 exp.JSONBContains: lambda self, e: self.binary(e, "?"), 311 exp.Pow: lambda self, e: self.binary(e, "^"), 312 exp.CurrentDate: no_paren_current_date_sql, 313 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 314 exp.DateAdd: _date_add_sql("+"), 315 exp.DateSub: _date_add_sql("-"), 316 exp.DateDiff: _date_diff_sql, 317 exp.LogicalOr: rename_func("BOOL_OR"), 318 exp.LogicalAnd: rename_func("BOOL_AND"), 319 exp.Min: min_or_least, 320 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 321 exp.ArrayContains: lambda self, e: self.binary(e, "@>"), 322 exp.ArrayContained: lambda self, e: self.binary(e, "<@"), 323 exp.RegexpLike: lambda self, e: self.binary(e, "~"), 324 exp.RegexpILike: lambda self, e: self.binary(e, "~*"), 325 exp.StrPosition: str_position_sql, 326 exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})", 327 exp.Substring: _substring_sql, 328 exp.TimestampTrunc: timestamptrunc_sql, 329 exp.TimeStrToTime: lambda self, e: f"CAST({self.sql(e, 'this')} AS TIMESTAMP)", 330 exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})", 331 exp.TableSample: no_tablesample_sql, 332 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 333 exp.Trim: trim_sql, 334 exp.TryCast: no_trycast_sql, 335 exp.UnixToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')})", 336 exp.DataType: _datatype_sql, 337 exp.GroupConcat: _string_agg_sql, 338 exp.Array: lambda self, e: f"{self.normalize_func('ARRAY')}({self.sql(e.expressions[0])})" 339 if isinstance(seq_get(e.expressions, 0), exp.Select) 340 else f"{self.normalize_func('ARRAY')}[{self.expressions(e, flat=True)}]", 341 } 342 343 PROPERTIES_LOCATION = { 344 **generator.Generator.PROPERTIES_LOCATION, # type: ignore 345 exp.TransientProperty: exp.Properties.Location.UNSUPPORTED, 346 }
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
- 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
- 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