sqlglot-odps 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sqlglot_odps/parser.py ADDED
@@ -0,0 +1,738 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import typing as t
5
+
6
+ from sqlglot import exp
7
+ from sqlglot.dialects.dialect import build_timetostr_or_tochar
8
+ from sqlglot.helper import seq_get
9
+ from sqlglot.parsers.hive import HiveParser
10
+ from sqlglot.tokens import TokenType
11
+ from sqlglot.trie import new_trie
12
+
13
+ WEEKDAYS = [
14
+ "monday",
15
+ "tuesday",
16
+ "wednesday",
17
+ "thursday",
18
+ "friday",
19
+ "saturday",
20
+ "sunday",
21
+ ]
22
+
23
+
24
+ def _build_dateadd(
25
+ args: t.List,
26
+ ) -> exp.DateAdd | exp.TimestampAdd | exp.DatetimeAdd | exp.TsOrDsAdd:
27
+ this = seq_get(args, 0)
28
+ expression = seq_get(args, 1)
29
+ unit = seq_get(args, 2)
30
+
31
+ if this.is_type("date"):
32
+ return exp.DateAdd(this=this, expression=expression, unit=unit)
33
+ if this.is_type("timestamp_ntz"):
34
+ return exp.TimestampAdd(this=this, expression=expression, unit=unit)
35
+ if this.is_type("datetime"):
36
+ return exp.DatetimeAdd(this=this, expression=expression, unit=unit)
37
+ return exp.TsOrDsAdd(this=this, expression=expression, unit=unit)
38
+
39
+
40
+ def _build_datetrunc(
41
+ args: t.List,
42
+ ) -> exp.DateTrunc | exp.TimestampTrunc | exp.DatetimeTrunc:
43
+ this = seq_get(args, 0)
44
+ unit = seq_get(args, 1)
45
+
46
+ if unit.name in [f"week({weekday})" for weekday in WEEKDAYS]:
47
+ unit = exp.WeekStart(
48
+ this=exp.var(re.sub(r"week\((.*)\)", r"\1", unit.name).upper())
49
+ )
50
+ elif unit.name == "week":
51
+ unit = exp.WeekStart(this=exp.var("MONDAY"))
52
+ else:
53
+ unit = exp.Var(this=unit.name.upper())
54
+
55
+ if this.is_type("date"):
56
+ return exp.DateTrunc(unit=unit, this=this)
57
+ if this.is_type("timestamp_ntz"):
58
+ return exp.TimestampTrunc(unit=unit, this=this)
59
+ if this.is_type("datetime"):
60
+ return exp.DatetimeTrunc(unit=unit, this=this)
61
+ return exp.DateTrunc(unit=unit, this=this)
62
+
63
+
64
+ class OdpsParser(HiveParser):
65
+ FUNCTIONS = {
66
+ **HiveParser.FUNCTIONS,
67
+ # Hive overrides: MaxCompute accepts date/datetime/timestamp/string directly
68
+ # without needing TsOrDsToDate wrapping
69
+ "DAY": exp.Day.from_arg_list,
70
+ "MONTH": exp.Month.from_arg_list,
71
+ "YEAR": exp.Year.from_arg_list,
72
+ # Hive override: MaxCompute DATE_FORMAT accepts date types directly (no TimeStrToTime)
73
+ "DATE_FORMAT": lambda args: exp.TimeToStr(
74
+ this=seq_get(args, 0), format=seq_get(args, 1)
75
+ ),
76
+ # Hive override: TO_DATE return type depends on args:
77
+ # TO_DATE(str) → DATE → TsOrDsToDate (no format)
78
+ # TO_DATE(str, fmt) → DATETIME → StrToTime (format present)
79
+ "TO_DATE": lambda args: (
80
+ exp.StrToTime(this=seq_get(args, 0), format=seq_get(args, 1))
81
+ if seq_get(args, 1) is not None
82
+ else exp.TsOrDsToDate(this=seq_get(args, 0))
83
+ ),
84
+ # Hive override: MaxCompute FROM_UNIXTIME takes 1 arg and returns DATETIME, not STRING
85
+ "FROM_UNIXTIME": lambda args: exp.UnixToTime(this=seq_get(args, 0)),
86
+ # Hive override: produce exp.DateSub so _dateadd_sql emits DATEADD(date, -n, unit)
87
+ # cleanly. Hive maps DATE_SUB to TsOrDsAdd(expression=Mul(n, -1)) which generates
88
+ # "3 * -1" in the output.
89
+ "DATE_SUB": lambda args: exp.DateSub(
90
+ this=seq_get(args, 0), expression=seq_get(args, 1)
91
+ ),
92
+ # Date arithmetic
93
+ "DATEADD": _build_dateadd,
94
+ "DATEDIFF": lambda args: exp.DateDiff(
95
+ this=seq_get(args, 0),
96
+ expression=seq_get(args, 1),
97
+ unit=seq_get(args, 2),
98
+ big_int=True,
99
+ ),
100
+ "ADD_MONTHS": exp.AddMonths.from_arg_list,
101
+ "MONTHS_BETWEEN": exp.MonthsBetween.from_arg_list,
102
+ # Date extraction
103
+ "DATEPART": lambda args: exp.Extract(
104
+ this=exp.Var(this=seq_get(args, 1).name.upper()),
105
+ expression=seq_get(args, 0),
106
+ ),
107
+ "DATETRUNC": _build_datetrunc,
108
+ "TRUNC_TIME": _build_datetrunc,
109
+ # TRUNC(n, d) → exp.Trunc (numeric truncation)
110
+ # TRUNC(dt, 'u') → _build_datetrunc (date truncation, same as TRUNC_TIME)
111
+ "TRUNC": lambda args: (
112
+ _build_datetrunc(args)
113
+ if seq_get(args, 1) is not None and seq_get(args, 1).is_string
114
+ else exp.Trunc(this=seq_get(args, 0), decimals=seq_get(args, 1))
115
+ ),
116
+ "DAYOFMONTH": exp.DayOfMonth.from_arg_list,
117
+ "DAYOFWEEK": exp.DayOfWeek.from_arg_list,
118
+ "DAYOFYEAR": exp.DayOfYear.from_arg_list,
119
+ "HOUR": exp.Hour.from_arg_list,
120
+ "MINUTE": exp.Minute.from_arg_list,
121
+ "SECOND": exp.Second.from_arg_list,
122
+ "QUARTER": exp.Quarter.from_arg_list,
123
+ "WEEKDAY": lambda args: (
124
+ exp.paren(exp.DayOfWeek(this=seq_get(args, 0)) + 5, copy=False) % 7
125
+ ),
126
+ "WEEKOFYEAR": exp.WeekOfYear.from_arg_list,
127
+ # Last/next day
128
+ "LAST_DAY": exp.LastDay.from_arg_list,
129
+ "LASTDAY": exp.LastDay.from_arg_list,
130
+ "NEXT_DAY": exp.NextDay.from_arg_list,
131
+ # Current date/time
132
+ "GETDATE": lambda args: exp.CurrentTimestamp(),
133
+ "CURRENT_TIMESTAMP": lambda args: exp.CurrentTimestamp(),
134
+ # Hive override: NOW() returns DATETIME (≈ TIMESTAMP) — map to CurrentTimestamp
135
+ # so cross-dialect output is CURRENT_TIMESTAMP, not CURRENT_DATETIME (BigQuery-specific).
136
+ "NOW": lambda args: exp.CurrentTimestamp(),
137
+ "CURRENT_TIMEZONE": lambda args: exp.CurrentTimezone(),
138
+ # Conversion
139
+ "TO_CHAR": build_timetostr_or_tochar,
140
+ "TO_MILLIS": exp.UnixMillis.from_arg_list,
141
+ "FROM_UTC_TIMESTAMP": lambda args: exp.ConvertTimezone(
142
+ source_tz=exp.Literal.string("UTC"),
143
+ target_tz=seq_get(args, 1),
144
+ timestamp=seq_get(args, 0),
145
+ ),
146
+ "ISDATE": lambda args: exp.not_(
147
+ exp.Is(
148
+ this=exp.TsOrDsToDate(
149
+ this=seq_get(args, 0), format=seq_get(args, 1), safe=True
150
+ ),
151
+ expression=exp.Null(),
152
+ )
153
+ ),
154
+ # String functions
155
+ "TOLOWER": exp.Lower.from_arg_list,
156
+ "TOUPPER": exp.Upper.from_arg_list,
157
+ "REGEXP_COUNT": exp.RegexpCount.from_arg_list,
158
+ "SPLIT_PART": exp.SplitPart.from_arg_list,
159
+ # SUBSTR is the preferred MaxCompute alias for SUBSTRING
160
+ "SUBSTR": exp.Substring.from_arg_list,
161
+ # Aggregate
162
+ "WM_CONCAT": lambda args: exp.GroupConcat(
163
+ this=seq_get(args, 1), separator=seq_get(args, 0)
164
+ ),
165
+ "COUNT_IF": exp.CountIf.from_arg_list,
166
+ "ARG_MAX": exp.ArgMax.from_arg_list,
167
+ "ARG_MIN": exp.ArgMin.from_arg_list,
168
+ "MAX_BY": exp.ArgMax.from_arg_list,
169
+ "MIN_BY": exp.ArgMin.from_arg_list,
170
+ "ANY_VALUE": exp.AnyValue.from_arg_list,
171
+ "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list,
172
+ "STDDEV_SAMP": exp.StddevSamp.from_arg_list,
173
+ "COVAR_POP": exp.CovarPop.from_arg_list,
174
+ "COVAR_SAMP": exp.CovarSamp.from_arg_list,
175
+ "CORR": exp.Corr.from_arg_list,
176
+ "MEDIAN": exp.Median.from_arg_list,
177
+ "PERCENTILE_APPROX": exp.ApproxQuantile.from_arg_list,
178
+ "BITWISE_AND_AGG": exp.BitwiseAndAgg.from_arg_list,
179
+ "BITWISE_OR_AGG": exp.BitwiseOrAgg.from_arg_list,
180
+ "BITWISE_XOR_AGG": exp.BitwiseXorAgg.from_arg_list,
181
+ # Array functions
182
+ "ALL_MATCH": exp.ArrayAll.from_arg_list,
183
+ "ANY_MATCH": exp.ArrayAny.from_arg_list,
184
+ "ARRAY_SORT": exp.ArraySort.from_arg_list,
185
+ "ARRAY_DISTINCT": exp.ArrayDistinct.from_arg_list,
186
+ "ARRAY_EXCEPT": exp.ArrayExcept.from_arg_list,
187
+ "ARRAY_JOIN": exp.ArrayToString.from_arg_list,
188
+ "ARRAY_MAX": exp.ArrayMax.from_arg_list,
189
+ "ARRAY_MIN": exp.ArrayMin.from_arg_list,
190
+ "ARRAYS_OVERLAP": exp.ArrayOverlaps.from_arg_list,
191
+ "ARRAYS_ZIP": lambda args: exp.ArraysZip(expressions=args),
192
+ "ARRAY_INTERSECT": exp.ArrayIntersect.from_arg_list,
193
+ "ARRAY_POSITION": exp.ArrayPosition.from_arg_list,
194
+ "ARRAY_REMOVE": exp.ArrayRemove.from_arg_list,
195
+ "ARRAY_CONTAINS": exp.ArrayContains.from_arg_list,
196
+ # Map functions
197
+ "MAP_CONCAT": exp.MapCat.from_arg_list,
198
+ "MAP_FROM_ENTRIES": exp.MapFromEntries.from_arg_list,
199
+ # JSON / misc
200
+ "FROM_JSON": exp.ParseJSON.from_arg_list,
201
+ "GET_USER_ID": lambda args: exp.CurrentUser(),
202
+ "REGEXP_SUBSTR": exp.RegexpExtract.from_arg_list,
203
+ "SLICE": exp.ArraySlice.from_arg_list,
204
+ }
205
+
206
+ PROPERTY_PARSERS = {
207
+ **HiveParser.PROPERTY_PARSERS,
208
+ # LIFECYCLE n — MaxCompute table retention in days. Stored as a generic
209
+ # exp.Property with a Var key so no custom expression class is needed and
210
+ # sqlglot's PROPERTIES_LOCATION contract is not broken.
211
+ "LIFECYCLE": lambda self: self.expression(
212
+ exp.Property(this=exp.var("LIFECYCLE"), value=self._parse_number())
213
+ ),
214
+ "RANGE": lambda self: self._parse_range_clustered_by(),
215
+ "AUTO": lambda self: self._parse_auto_partition(),
216
+ }
217
+
218
+ STATEMENT_PARSERS = {
219
+ **HiveParser.STATEMENT_PARSERS,
220
+ TokenType.SHOW: lambda self: self._parse_show(),
221
+ }
222
+
223
+ QUERY_MODIFIER_PARSERS = {
224
+ **HiveParser.QUERY_MODIFIER_PARSERS,
225
+ TokenType.SORT_BY: lambda self: self._parse_sort_modifier(),
226
+ }
227
+
228
+ SHOW_PARSERS = {
229
+ "TABLES": lambda self: self._parse_show_listing("TABLES", scoped=True),
230
+ "SCHEMAS": lambda self: self._parse_show_listing("SCHEMAS", scoped=True),
231
+ "DATABASES": lambda self: self._parse_show_listing("DATABASES"),
232
+ "FUNCTIONS": lambda self: self._parse_show_listing("FUNCTIONS"),
233
+ "BUILTIN FUNCTIONS": lambda self: self._parse_show_listing("BUILTIN FUNCTIONS"),
234
+ "PARTITIONS": lambda self: self._parse_show_target(
235
+ "PARTITIONS", partition=True
236
+ ),
237
+ "TBLPROPERTIES": lambda self: self._parse_show_target(
238
+ "TBLPROPERTIES", property_name=True
239
+ ),
240
+ "CREATE TABLE": lambda self: self._parse_show_target("CREATE TABLE"),
241
+ "CREATE VIEW": lambda self: self._parse_show_target("CREATE VIEW"),
242
+ "CREATE MATERIALIZED VIEW": lambda self: self._parse_show_target(
243
+ "CREATE MATERIALIZED VIEW"
244
+ ),
245
+ "CREATE TASK": lambda self: self._parse_show_target("CREATE TASK"),
246
+ }
247
+
248
+ SHOW_TRIE = new_trie(key.split(" ") for key in SHOW_PARSERS)
249
+
250
+ TRANSFER_PARSERS = {
251
+ "READ": lambda self: self._parse_read(),
252
+ "UNLOAD": lambda self: self._parse_unload(),
253
+ }
254
+
255
+ def _parse_statement(self):
256
+ if self._curr.token_type == TokenType.BEGIN:
257
+ self.raise_error(
258
+ "Compound BEGIN statements require the MaxCompute script parser"
259
+ )
260
+ if self._curr.token_type == TokenType.VAR:
261
+ parse_command = self.TRANSFER_PARSERS.get(self._curr.text.upper())
262
+ if parse_command:
263
+ comments = self._curr.comments
264
+ self._advance()
265
+ statement = parse_command(self)
266
+ statement.add_comments(comments, prepend=True)
267
+ return statement
268
+ if self._curr.token_type == TokenType.PARAMETER and self._curr.text == "@":
269
+ assign = seq_get(self._tokens, self._index + 2)
270
+ if assign and assign.token_type == TokenType.COLON_EQ:
271
+ self._advance()
272
+ variable = self._parse_parameter()
273
+ self._match(TokenType.COLON_EQ)
274
+ value = self._parse_select(nested=True) or self._parse_expression()
275
+ return self.expression(exp.PropertyEQ(this=variable, expression=value))
276
+ return super()._parse_statement()
277
+
278
+ def _parse_transfer_table(self):
279
+ table = self._parse_table_parts(schema=True)
280
+ table.set("partition", self._parse_partition())
281
+ return table
282
+
283
+ def _parse_read(self):
284
+ table = self._parse_table_parts(schema=True)
285
+ columns = None
286
+ if self._match(TokenType.L_PAREN, advance=False):
287
+ columns = self._parse_wrapped_csv(self._parse_column)
288
+ if not columns:
289
+ self.raise_error("Expected column names in READ")
290
+ table.set("partition", self._parse_partition())
291
+ count = self._parse_number()
292
+ node = self.expression(
293
+ exp.Select(
294
+ expressions=columns or [exp.Star()],
295
+ from_=exp.From(this=table),
296
+ limit=exp.Limit(expression=count) if count is not None else None,
297
+ )
298
+ )
299
+ node.set("read", True)
300
+ return node
301
+
302
+ def _parse_unload(self):
303
+ if not self._match(TokenType.FROM):
304
+ self.raise_error("Expected FROM after UNLOAD")
305
+ source = (
306
+ self._parse_select(nested=True)
307
+ if self._match(TokenType.L_PAREN, advance=False)
308
+ else self._parse_transfer_table()
309
+ )
310
+ overwrite = self._match(TokenType.OVERWRITE)
311
+ if not overwrite and not self._match(TokenType.INTO):
312
+ self.raise_error("Expected INTO or OVERWRITE in UNLOAD")
313
+ options = []
314
+ while self._match_texts({"LOCATION", "ROW", "STORED", "WITH"}, advance=False):
315
+ prop = self._parse_property()
316
+ if not prop:
317
+ break
318
+ options.append(prop)
319
+ if not any(isinstance(prop, exp.LocationProperty) for prop in options):
320
+ self.raise_error("Expected a LOCATION in UNLOAD")
321
+ node = exp.Export(this=source, options=options)
322
+ node.set("transfer", "UNLOAD")
323
+ node.set("overwrite", overwrite)
324
+ return node
325
+
326
+ def _parse_show_listing(self, kind, scoped=False):
327
+ scope = None
328
+ if scoped and self._match_set((TokenType.FROM, TokenType.IN)):
329
+ scope = self._parse_id_var()
330
+ if scope is None:
331
+ self.raise_error("Expected a schema or project after FROM or IN")
332
+ explicit_like = self._match(TokenType.LIKE)
333
+ like = None
334
+ if explicit_like or self._curr:
335
+ like = self._parse_string() or self._parse_id_var()
336
+ if explicit_like and like is None:
337
+ if kind == "DATABASES" or self._curr:
338
+ self.raise_error("Expected a pattern after LIKE")
339
+ else:
340
+ like = exp.to_identifier("LIKE")
341
+ return self.expression(exp.Show(this=kind, scope=scope, like=like))
342
+
343
+ def _parse_show_target(self, kind, partition=False, property_name=False):
344
+ target = self._parse_table_parts(schema=True)
345
+ if partition:
346
+ target.set("partition", self._parse_partition())
347
+ prop = None
348
+ if property_name and self._match(TokenType.L_PAREN):
349
+ prop = self._parse_string()
350
+ if prop is None:
351
+ self.raise_error("Expected property name in SHOW TBLPROPERTIES")
352
+ self._match_r_paren()
353
+ node = self.expression(exp.Show(this=kind, target=target))
354
+ node.set("property_name", prop)
355
+ return node
356
+
357
+ def _parse_describe(self):
358
+ if self._prev.text.upper() != "EXPLAIN":
359
+ return super()._parse_describe()
360
+
361
+ subject = self._parse_select(nested=True)
362
+ if not isinstance(subject, exp.Query):
363
+ self.raise_error("Expected a query after EXPLAIN")
364
+ return self.expression(exp.Describe(this=subject, kind="EXPLAIN"))
365
+
366
+ def _parse_create(self):
367
+ index = self._index
368
+ temporary = self._match(TokenType.TEMPORARY)
369
+ if self._match(TokenType.FUNCTION):
370
+ name = self._parse_table_parts(schema=True)
371
+ if self._match(TokenType.ALIAS) and (
372
+ implementation := self._parse_string()
373
+ ):
374
+ properties = []
375
+ if temporary:
376
+ properties.append(exp.TemporaryProperty())
377
+ udf = self.expression(
378
+ exp.Create(
379
+ this=name,
380
+ kind="FUNCTION",
381
+ expression=implementation,
382
+ properties=exp.Properties(expressions=properties)
383
+ if properties
384
+ else None,
385
+ )
386
+ )
387
+ if self._match(TokenType.USING):
388
+ resources = self._parse_csv(self._parse_udf_resource)
389
+ if not resources:
390
+ self.raise_error("Expected resources after USING")
391
+ udf.set("resources", resources)
392
+ return udf
393
+ self._retreat(index)
394
+ return super()._parse_create()
395
+
396
+ def _parse_udf_resource(self):
397
+ kind = (
398
+ exp.var(self._prev.text.upper())
399
+ if self._match_texts({"JAR", "FILE", "ARCHIVE"})
400
+ else None
401
+ )
402
+ path = self._parse_string()
403
+ if path is None:
404
+ self.raise_error("Expected a function resource path")
405
+ return exp.Property(this=kind, value=path)
406
+
407
+ def _parse_version(self):
408
+ if self._curr.token_type == TokenType.FOR:
409
+ phrase = self._curr.text.upper().split()
410
+ if len(phrase) < 2 or phrase[0] not in {"VERSION", "TIMESTAMP"}:
411
+ return None
412
+ self._advance()
413
+ kind, modifier = phrase[0], " ".join(phrase[1:])
414
+ start = self._parse_equality()
415
+ if start is None:
416
+ self.raise_error("Expected a time travel value")
417
+ if modifier == "BETWEEN":
418
+ if not self._match(TokenType.AND):
419
+ self.raise_error("Expected AND in time travel range")
420
+ end = self._parse_equality()
421
+ if end is None:
422
+ self.raise_error("Expected both bounds of time travel range")
423
+ start = exp.Tuple(expressions=[start, end])
424
+ return self.expression(
425
+ exp.Version(this=kind, kind=modifier, expression=start)
426
+ )
427
+ return None
428
+
429
+ def _parse_sort_modifier(self):
430
+ keyword = self._curr.text.upper()
431
+ if keyword == "SORT BY":
432
+ return "sort", self._parse_sort(exp.Sort, TokenType.SORT_BY)
433
+ self._advance()
434
+ wrapped = self._match(TokenType.L_PAREN)
435
+ columns = self._parse_csv(self._parse_column)
436
+ if not columns:
437
+ self.raise_error("Expected a column list in ZORDER BY")
438
+ if wrapped:
439
+ self._match_r_paren()
440
+ zorder = self.expression(exp.Sort(expressions=columns))
441
+ zorder.set("wrapped", wrapped)
442
+ return "zorder", zorder
443
+
444
+ def _parse_grant_principal(self):
445
+ if self._match_text_seq("USER"):
446
+ return self.expression(
447
+ exp.GrantPrincipal(this=self._parse_id_var(), kind="USER")
448
+ )
449
+ return super()._parse_grant_principal()
450
+
451
+ def _parse_parameter(self):
452
+ native = self._prev.text == "@"
453
+ node = super()._parse_parameter()
454
+ if native:
455
+ node.set("native", True)
456
+ return node
457
+
458
+ ALTER_PARSERS = {
459
+ **HiveParser.ALTER_PARSERS,
460
+ "ENABLE": lambda self: self._parse_alter_lifecycle(),
461
+ "DISABLE": lambda self: self._parse_alter_lifecycle(),
462
+ "COMPACT": lambda self: self._parse_compact(),
463
+ }
464
+
465
+ def _parse_table_alias(self, alias_tokens=None):
466
+ if (
467
+ self._curr.token_type != TokenType.IDENTIFIER
468
+ and self._curr.text.upper() == "LOCAL"
469
+ and self._next.token_type == TokenType.ORDER_BY
470
+ ):
471
+ self.raise_error("Unexpected LOCAL before ORDER BY")
472
+ return super()._parse_table_alias(alias_tokens=alias_tokens)
473
+
474
+ def _parse_write_table(self, alias_tokens=None):
475
+ table = self._parse_table(schema=True, parse_partition=True)
476
+ if isinstance(table, exp.Table) and not self._match_text_seq(
477
+ "EVOLVE", "COLUMNS", advance=False
478
+ ):
479
+ table.set("alias", self._parse_table_alias(alias_tokens=alias_tokens))
480
+ return table
481
+
482
+ def _parse_delete(self):
483
+ if not self._match(TokenType.FROM):
484
+ self.raise_error("Expected FROM after DELETE")
485
+ return self.expression(
486
+ exp.Delete(this=self._parse_write_table(), where=self._parse_where())
487
+ )
488
+
489
+ def _parse_update(self):
490
+ table = self._parse_write_table(self.UPDATE_ALIAS_TOKENS)
491
+ evolve = self._match_text_seq("EVOLVE", "COLUMNS")
492
+ if not self._match(TokenType.SET):
493
+ self.raise_error("Expected SET after UPDATE target")
494
+ assignments = self._parse_csv(self._parse_equality)
495
+ if not assignments or not all(isinstance(item, exp.EQ) for item in assignments):
496
+ self.raise_error("Expected column assignments after SET")
497
+ node = self.expression(
498
+ exp.Update(
499
+ this=table,
500
+ expressions=assignments,
501
+ from_=self._parse_from(joins=True),
502
+ where=self._parse_where(),
503
+ )
504
+ )
505
+ if evolve:
506
+ node.set("evolve", True)
507
+ return node
508
+
509
+ def _parse_truncate_table(self):
510
+ if not self._match(TokenType.TABLE):
511
+ return super()._parse_truncate_table()
512
+ table = self._parse_table_parts(schema=True)
513
+ partitions = self._parse_csv(self._parse_partition)
514
+ columns = None
515
+ if self._match_text_seq("COLUMNS"):
516
+ self._match_l_paren()
517
+ columns = self._parse_csv(self._parse_id_var)
518
+ if not columns:
519
+ self.raise_error("Expected column names after COLUMNS")
520
+ self._match_r_paren()
521
+ node = self.expression(exp.TruncateTable(expressions=[table]))
522
+ node.set("partitions", partitions or None)
523
+ node.set("columns", columns)
524
+ return node
525
+
526
+ def _parse_alter_table_add(self):
527
+ index = self._index
528
+ exists = self._parse_exists(not_=True)
529
+ if not self._match(TokenType.PARTITION, advance=False):
530
+ self._retreat(index)
531
+ return super()._parse_alter_table_add()
532
+
533
+ def parse_partition():
534
+ return self.expression(
535
+ exp.AddPartition(
536
+ this=self._parse_partition(),
537
+ location=self._parse_property()
538
+ if self._match_text_seq("LOCATION", advance=False)
539
+ else None,
540
+ )
541
+ )
542
+
543
+ first = parse_partition()
544
+ first.set("exists", exists)
545
+ additional = []
546
+ while self._match(TokenType.PARTITION, advance=False):
547
+ additional.append(parse_partition())
548
+ first.set("additional_partitions", additional or None)
549
+ return [first]
550
+
551
+ def _parse_alter_lifecycle(self):
552
+ operation = self._prev.text.upper()
553
+ if self._match_text_seq("LIFECYCLE"):
554
+ return exp.var(f"{operation} LIFECYCLE")
555
+ return None
556
+
557
+ def _parse_compact(self):
558
+ mode = self._parse_string()
559
+ return (
560
+ exp.Command(
561
+ this="COMPACT", expression=self._find_sql(self._prev, self._prev)
562
+ )
563
+ if mode is not None
564
+ else None
565
+ )
566
+
567
+ def _parse_select_query(
568
+ self,
569
+ nested=False,
570
+ table=False,
571
+ parse_subquery_alias=True,
572
+ parse_set_operation=True,
573
+ ):
574
+ # FROM-first queries and multi-inserts share the same source production.
575
+ if self._match(TokenType.WITH, advance=False):
576
+ cte = self._parse_with()
577
+ if cte:
578
+ statement = self._parse_statement()
579
+ while isinstance(statement, exp.Subquery) and statement.is_wrapper:
580
+ statement = statement.this
581
+ if isinstance(statement, exp.MultitableInserts) or (
582
+ statement is not None and "with_" in statement.arg_types
583
+ ):
584
+ statement.set("with_", cte)
585
+ return statement
586
+ self.raise_error("Expected a query or write statement after WITH")
587
+ return cte
588
+
589
+ if self._match(TokenType.FROM, advance=False):
590
+ source = self._parse_from(joins=True)
591
+ if self._match(TokenType.INSERT):
592
+ branches = [self._parse_insert_branch()]
593
+ while self._match(TokenType.INSERT):
594
+ branches.append(self._parse_insert_branch())
595
+ return self.expression(
596
+ exp.MultitableInserts(
597
+ kind="FROM", expressions=branches, source=source
598
+ )
599
+ )
600
+
601
+ query = self._parse_source_select(parse_set_operation=False)
602
+ if isinstance(query, exp.Select):
603
+ if query.args.get("from_"):
604
+ self.raise_error("FROM-first query already has a source")
605
+ query.set("from_", source)
606
+ # Put joins at the same level as SELECT-first queries.
607
+ query.set("joins", source.this.args.pop("joins", None))
608
+ return self._parse_set_operations(query) if parse_set_operation else query
609
+
610
+ query = super()._parse_select_query(
611
+ nested=nested,
612
+ table=table,
613
+ parse_subquery_alias=parse_subquery_alias,
614
+ parse_set_operation=parse_set_operation,
615
+ )
616
+ if isinstance(query, exp.Select) and not query.expressions:
617
+ self.raise_error("Expected projections after SELECT")
618
+ return query
619
+
620
+ def _parse_source_select(self, parse_set_operation=True):
621
+ clauses = self._parse_query_modifiers(exp.Select())
622
+ query = self._parse_select(nested=True, parse_set_operation=False)
623
+ if not isinstance(query, (exp.Select, exp.Subquery, exp.SetOperation)):
624
+ self.raise_error("Expected SELECT after shared source or insert target")
625
+ return query
626
+ for key, value in clauses.args.items():
627
+ if not isinstance(query, exp.Select) or query.args.get(key):
628
+ self.raise_error(f"Unexpected or duplicate {key} clause before SELECT")
629
+ query.set(key, value)
630
+ return self._parse_set_operations(query) if parse_set_operation else query
631
+
632
+ def _parse_maxcompute_insert_target(self):
633
+ hint = self._parse_hint()
634
+ overwrite = self._match(TokenType.OVERWRITE)
635
+ if not overwrite and not self._match(TokenType.INTO):
636
+ self.raise_error("Expected INTO or OVERWRITE after INSERT")
637
+
638
+ local = overwrite and self._match_text_seq("LOCAL")
639
+ if overwrite and self._match_text_seq("DIRECTORY"):
640
+ target = self.expression(
641
+ exp.Directory(
642
+ this=self._parse_string(),
643
+ local=local,
644
+ row_format=self._parse_row_format(match_row=True),
645
+ )
646
+ )
647
+ else:
648
+ if local:
649
+ self.raise_error("Expected DIRECTORY after LOCAL")
650
+ self._match(TokenType.TABLE)
651
+ target = self._parse_insert_table()
652
+ stored = None
653
+ if isinstance(target, exp.Directory) and self._match_text_seq("STORED"):
654
+ stored = self._parse_stored()
655
+ exists = overwrite and self._parse_exists(not_=True)
656
+ return self.expression(
657
+ exp.Insert(
658
+ this=target,
659
+ overwrite=overwrite,
660
+ exists=exists,
661
+ hint=hint,
662
+ stored=stored,
663
+ )
664
+ )
665
+
666
+ def _parse_insert(self):
667
+ insert = self._parse_maxcompute_insert_target()
668
+ body = self._parse_derived_table_values() or self._parse_select(nested=True)
669
+ if not isinstance(body, (exp.Query, exp.Values)):
670
+ self.raise_error("Expected a query or VALUES after INSERT target")
671
+ insert.set("expression", body)
672
+ return insert
673
+
674
+ def _parse_insert_branch(self):
675
+ insert = self._parse_maxcompute_insert_target()
676
+ query = self._parse_source_select()
677
+ operands = [query]
678
+ while operands:
679
+ operand = operands.pop()
680
+ if isinstance(operand, exp.SetOperation):
681
+ operands.extend((operand.this, operand.expression))
682
+ elif isinstance(operand, exp.Subquery):
683
+ operands.append(operand.this)
684
+ elif isinstance(operand, exp.Select) and operand.args.get("from_"):
685
+ self.raise_error(
686
+ "Multi-insert branch SELECT uses the shared FROM source"
687
+ )
688
+ insert.set("expression", query)
689
+ return insert
690
+
691
+ def _parse_auto_partition(
692
+ self,
693
+ ) -> exp.PartitionedByProperty | exp.AutoRefreshProperty | None:
694
+ if self._match(TokenType.PARTITION_BY):
695
+ self._match_l_paren()
696
+ expression = self._parse_expression()
697
+ if expression is None:
698
+ self.raise_error("Expected an expression in AUTO PARTITIONED BY")
699
+ self._match_r_paren()
700
+ prop = exp.PartitionedByProperty(this=expression)
701
+ prop.set("auto", True)
702
+ return prop
703
+ return self._parse_auto_property()
704
+
705
+ def _parse_range_clustered_by(self) -> exp.ClusteredByProperty:
706
+ if not self._match_text_seq("CLUSTERED"):
707
+ self._retreat(self._index - 1)
708
+ return self._parse_dict_range(this="RANGE")
709
+ prop = self._parse_clustered_by()
710
+ prop.args["range"] = True
711
+ return prop
712
+
713
+ def _parse_clustered_by(self):
714
+ if not self._match_text_seq("BY"):
715
+ self.raise_error("Expected BY after CLUSTERED")
716
+ auto = self._match_text_seq("AUTO")
717
+ columns, sorted_by, buckets = None, None, None
718
+ if self._match(TokenType.L_PAREN, advance=False):
719
+ columns = self._parse_wrapped_csv(
720
+ lambda: self._parse_ordered(self._parse_column)
721
+ )
722
+ if not columns:
723
+ self.raise_error("Expected clustering columns")
724
+ if self._match_text_seq("SORTED", "BY"):
725
+ sorted_by = self._parse_wrapped_csv(
726
+ lambda: self._parse_ordered(self._parse_column)
727
+ )
728
+ if not sorted_by:
729
+ self.raise_error("Expected sort columns")
730
+ if self._match(TokenType.INTO):
731
+ buckets = self._parse_number()
732
+ if buckets is None or not self._match_text_seq("BUCKETS"):
733
+ self.raise_error("Expected a bucket count followed by BUCKETS")
734
+ prop = exp.ClusteredByProperty(
735
+ expressions=columns, sorted_by=sorted_by, buckets=buckets
736
+ )
737
+ prop.set("auto", auto)
738
+ return prop