pylegend 0.10.0__py3-none-any.whl → 0.12.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.
- pylegend/core/database/sql_to_string/db_extension.py +68 -6
- pylegend/core/language/legendql_api/legendql_api_custom_expressions.py +190 -5
- pylegend/core/language/pandas_api/pandas_api_series.py +3 -0
- pylegend/core/sql/metamodel.py +4 -1
- pylegend/core/tds/legendql_api/frames/functions/legendql_api_distinct_function.py +53 -7
- pylegend/core/tds/legendql_api/frames/legendql_api_base_tds_frame.py +146 -4
- pylegend/core/tds/legendql_api/frames/legendql_api_tds_frame.py +33 -2
- pylegend/core/tds/pandas_api/frames/functions/aggregate_function.py +221 -96
- pylegend/core/tds/pandas_api/frames/functions/assign_function.py +65 -23
- pylegend/core/tds/pandas_api/frames/functions/drop.py +3 -3
- pylegend/core/tds/pandas_api/frames/functions/dropna.py +167 -0
- pylegend/core/tds/pandas_api/frames/functions/fillna.py +162 -0
- pylegend/core/tds/pandas_api/frames/functions/filter.py +10 -5
- pylegend/core/tds/pandas_api/frames/functions/merge.py +513 -0
- pylegend/core/tds/pandas_api/frames/functions/rename.py +214 -0
- pylegend/core/tds/pandas_api/frames/functions/truncate_function.py +151 -120
- pylegend/core/tds/pandas_api/frames/pandas_api_applied_function_tds_frame.py +7 -3
- pylegend/core/tds/pandas_api/frames/pandas_api_base_tds_frame.py +559 -18
- pylegend/core/tds/pandas_api/frames/pandas_api_groupby_tds_frame.py +325 -0
- pylegend/core/tds/pandas_api/frames/pandas_api_tds_frame.py +218 -12
- pylegend/extensions/tds/abstract/csv_tds_frame.py +95 -0
- pylegend/extensions/tds/legendql_api/frames/legendql_api_csv_input_frame.py +36 -0
- pylegend/extensions/tds/pandas_api/frames/pandas_api_legend_function_input_frame.py +9 -4
- pylegend/extensions/tds/pandas_api/frames/pandas_api_legend_service_input_frame.py +12 -5
- pylegend/extensions/tds/pandas_api/frames/pandas_api_table_spec_input_frame.py +12 -4
- {pylegend-0.10.0.dist-info → pylegend-0.12.0.dist-info}/METADATA +1 -1
- {pylegend-0.10.0.dist-info → pylegend-0.12.0.dist-info}/RECORD +31 -24
- {pylegend-0.10.0.dist-info → pylegend-0.12.0.dist-info}/WHEEL +0 -0
- {pylegend-0.10.0.dist-info → pylegend-0.12.0.dist-info}/licenses/LICENSE +0 -0
- {pylegend-0.10.0.dist-info → pylegend-0.12.0.dist-info}/licenses/LICENSE.spdx +0 -0
- {pylegend-0.10.0.dist-info → pylegend-0.12.0.dist-info}/licenses/NOTICE +0 -0
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
# Copyright 2025 Goldman Sachs
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
from pylegend._typing import (
|
|
16
|
+
PyLegendList,
|
|
17
|
+
PyLegendSequence,
|
|
18
|
+
PyLegendUnion,
|
|
19
|
+
PyLegendOptional,
|
|
20
|
+
PyLegendTuple,
|
|
21
|
+
)
|
|
22
|
+
from pylegend.core.language import (
|
|
23
|
+
PyLegendBoolean,
|
|
24
|
+
PyLegendBooleanLiteralExpression,
|
|
25
|
+
PyLegendPrimitive,
|
|
26
|
+
)
|
|
27
|
+
from pylegend.core.language.pandas_api.pandas_api_tds_row import PandasApiTdsRow
|
|
28
|
+
from pylegend.core.language.shared.helpers import generate_pure_lambda
|
|
29
|
+
from pylegend.core.language.shared.literal_expressions import convert_literal_to_literal_expression
|
|
30
|
+
from pylegend.core.sql.metamodel import (
|
|
31
|
+
QuerySpecification,
|
|
32
|
+
Select,
|
|
33
|
+
SelectItem,
|
|
34
|
+
SingleColumn,
|
|
35
|
+
AliasedRelation,
|
|
36
|
+
TableSubquery,
|
|
37
|
+
Query,
|
|
38
|
+
Join,
|
|
39
|
+
JoinType,
|
|
40
|
+
JoinOn,
|
|
41
|
+
QualifiedNameReference,
|
|
42
|
+
QualifiedName,
|
|
43
|
+
)
|
|
44
|
+
from pylegend.core.tds.pandas_api.frames.pandas_api_applied_function_tds_frame import PandasApiAppliedFunction
|
|
45
|
+
from pylegend.core.tds.pandas_api.frames.pandas_api_base_tds_frame import PandasApiBaseTdsFrame
|
|
46
|
+
from pylegend.core.tds.pandas_api.frames.pandas_api_tds_frame import PandasApiTdsFrame
|
|
47
|
+
from pylegend.core.tds.sql_query_helpers import copy_query, create_sub_query, extract_columns_for_subquery
|
|
48
|
+
from pylegend.core.tds.tds_column import TdsColumn
|
|
49
|
+
from pylegend.core.tds.tds_frame import FrameToSqlConfig, FrameToPureConfig
|
|
50
|
+
|
|
51
|
+
__all__: PyLegendSequence[str] = [
|
|
52
|
+
"PandasApiMergeFunction"
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class PandasApiMergeFunction(PandasApiAppliedFunction):
|
|
57
|
+
__base_frame: PandasApiBaseTdsFrame
|
|
58
|
+
__other_frame: PandasApiBaseTdsFrame
|
|
59
|
+
__how: PyLegendOptional[str]
|
|
60
|
+
__on: PyLegendOptional[PyLegendUnion[str, PyLegendSequence[str]]]
|
|
61
|
+
__left_on: PyLegendOptional[PyLegendUnion[str, PyLegendSequence[str]]]
|
|
62
|
+
__right_on: PyLegendOptional[PyLegendUnion[str, PyLegendSequence[str]]]
|
|
63
|
+
__left_index: PyLegendOptional[bool]
|
|
64
|
+
__right_index: PyLegendOptional[bool]
|
|
65
|
+
__sort: PyLegendOptional[bool]
|
|
66
|
+
__suffixes: PyLegendOptional[
|
|
67
|
+
PyLegendUnion[
|
|
68
|
+
PyLegendTuple[PyLegendUnion[str, None], PyLegendUnion[str, None]],
|
|
69
|
+
PyLegendList[PyLegendUnion[str, None]],
|
|
70
|
+
]
|
|
71
|
+
]
|
|
72
|
+
__indicator: PyLegendOptional[PyLegendUnion[bool, str]]
|
|
73
|
+
__validate: PyLegendOptional[str]
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def name(cls) -> str:
|
|
77
|
+
return "merge" # pragma: no cover
|
|
78
|
+
|
|
79
|
+
def __init__(
|
|
80
|
+
self,
|
|
81
|
+
base_frame: PandasApiBaseTdsFrame,
|
|
82
|
+
other_frame: PandasApiBaseTdsFrame,
|
|
83
|
+
how: PyLegendOptional[str],
|
|
84
|
+
on: PyLegendOptional[PyLegendUnion[str, PyLegendSequence[str]]],
|
|
85
|
+
left_on: PyLegendOptional[PyLegendUnion[str, PyLegendSequence[str]]],
|
|
86
|
+
right_on: PyLegendOptional[PyLegendUnion[str, PyLegendSequence[str]]],
|
|
87
|
+
left_index: PyLegendOptional[bool],
|
|
88
|
+
right_index: PyLegendOptional[bool],
|
|
89
|
+
sort: PyLegendOptional[bool],
|
|
90
|
+
suffixes: PyLegendOptional[
|
|
91
|
+
PyLegendUnion[
|
|
92
|
+
PyLegendTuple[PyLegendUnion[str, None], PyLegendUnion[str, None]],
|
|
93
|
+
PyLegendList[PyLegendUnion[str, None]],
|
|
94
|
+
]
|
|
95
|
+
],
|
|
96
|
+
indicator: PyLegendOptional[PyLegendUnion[bool, str]],
|
|
97
|
+
validate: PyLegendOptional[str]
|
|
98
|
+
) -> None:
|
|
99
|
+
self.__base_frame = base_frame
|
|
100
|
+
self.__other_frame = other_frame
|
|
101
|
+
self.__on = on
|
|
102
|
+
self.__left_on = left_on
|
|
103
|
+
self.__right_on = right_on
|
|
104
|
+
self.__left_index = left_index
|
|
105
|
+
self.__right_index = right_index
|
|
106
|
+
self.__sort = sort
|
|
107
|
+
self.__how = how
|
|
108
|
+
self.__suffixes = suffixes
|
|
109
|
+
self.__indicator = indicator
|
|
110
|
+
self.__validate = validate
|
|
111
|
+
self.__sortkeys = [] # type: PyLegendList[str]
|
|
112
|
+
|
|
113
|
+
def get_sort_keys(self) -> PyLegendList[str]:
|
|
114
|
+
return self.__sortkeys
|
|
115
|
+
|
|
116
|
+
# Key resolution helpers
|
|
117
|
+
def __normalize_keys(
|
|
118
|
+
self,
|
|
119
|
+
candidate: PyLegendUnion[str, PyLegendSequence[str], None]
|
|
120
|
+
) -> PyLegendList[str]:
|
|
121
|
+
if candidate is None:
|
|
122
|
+
return []
|
|
123
|
+
return [candidate] if isinstance(candidate, str) else list(candidate)
|
|
124
|
+
|
|
125
|
+
def __derive_key_pairs(self) -> PyLegendList[PyLegendTuple[str, str]]:
|
|
126
|
+
|
|
127
|
+
if self.__how.lower() == "cross": # type: ignore
|
|
128
|
+
return []
|
|
129
|
+
|
|
130
|
+
left_cols = [c.get_name() for c in self.__base_frame.columns()]
|
|
131
|
+
right_cols = [c.get_name() for c in self.__other_frame.columns()]
|
|
132
|
+
|
|
133
|
+
if self.__on is not None and (self.__left_on is not None or self.__right_on is not None):
|
|
134
|
+
raise ValueError('Can only pass argument "on" OR "left_on" and "right_on", not a combination of both.')
|
|
135
|
+
if self.__on is not None:
|
|
136
|
+
on_keys = self.__normalize_keys(self.__on)
|
|
137
|
+
for k in on_keys:
|
|
138
|
+
if k not in left_cols or k not in right_cols:
|
|
139
|
+
raise KeyError(f"'{k}' not found")
|
|
140
|
+
return [(k, k) for k in on_keys]
|
|
141
|
+
|
|
142
|
+
left_keys = self.__normalize_keys(self.__left_on)
|
|
143
|
+
right_keys = self.__normalize_keys(self.__right_on)
|
|
144
|
+
|
|
145
|
+
if left_keys or right_keys:
|
|
146
|
+
if len(left_keys) != len(right_keys):
|
|
147
|
+
print("came here")
|
|
148
|
+
raise ValueError("len(right_on) must equal len(left_on)")
|
|
149
|
+
for lk in left_keys:
|
|
150
|
+
if lk not in left_cols:
|
|
151
|
+
raise KeyError(f"'{lk}' not found")
|
|
152
|
+
for rk in right_keys:
|
|
153
|
+
if rk not in right_cols:
|
|
154
|
+
raise KeyError(f"'{rk}' not found")
|
|
155
|
+
|
|
156
|
+
return list(zip(left_keys, right_keys))
|
|
157
|
+
|
|
158
|
+
# Infer intersection by default
|
|
159
|
+
inferred = [c for c in left_cols if c in right_cols]
|
|
160
|
+
return [(k, k) for k in inferred]
|
|
161
|
+
|
|
162
|
+
def __normalize_suffixes(self) -> None:
|
|
163
|
+
# Convert None to empty string and coerce to list[str]
|
|
164
|
+
left = self.__suffixes[0] or "" # type: ignore
|
|
165
|
+
right = self.__suffixes[1] or "" # type: ignore
|
|
166
|
+
|
|
167
|
+
self.__suffixes = [left, right]
|
|
168
|
+
|
|
169
|
+
# Internal auto join condition builder (returns PyLegendBoolean expression)
|
|
170
|
+
def __build_condition(self) -> PyLegendBoolean:
|
|
171
|
+
key_pairs = self.__derive_key_pairs()
|
|
172
|
+
left_row = PandasApiTdsRow.from_tds_frame("left", self.__base_frame)
|
|
173
|
+
right_row = PandasApiTdsRow.from_tds_frame("right", self.__other_frame)
|
|
174
|
+
|
|
175
|
+
expr = None
|
|
176
|
+
for left_key, right_key in key_pairs:
|
|
177
|
+
part = (left_row[left_key] == right_row[right_key])
|
|
178
|
+
expr = part if expr is None else (expr & part)
|
|
179
|
+
return expr # type: ignore
|
|
180
|
+
|
|
181
|
+
def __join_type(self) -> JoinType:
|
|
182
|
+
how_lower = self.__how.lower() # type: ignore
|
|
183
|
+
if how_lower == "inner":
|
|
184
|
+
return JoinType.INNER
|
|
185
|
+
if how_lower == "left":
|
|
186
|
+
return JoinType.LEFT
|
|
187
|
+
if how_lower == "right":
|
|
188
|
+
return JoinType.RIGHT
|
|
189
|
+
if how_lower == "outer":
|
|
190
|
+
return JoinType.FULL
|
|
191
|
+
if how_lower == "cross":
|
|
192
|
+
return JoinType.CROSS
|
|
193
|
+
raise ValueError("do not recognize join method " + self.__how) # type: ignore
|
|
194
|
+
|
|
195
|
+
def to_sql(self, config: FrameToSqlConfig) -> QuerySpecification:
|
|
196
|
+
db_extension = config.sql_to_string_generator().get_db_extension()
|
|
197
|
+
left_query = copy_query(self.__base_frame.to_sql_query_object(config))
|
|
198
|
+
right_query = copy_query(self.__other_frame.to_sql_query_object(config))
|
|
199
|
+
|
|
200
|
+
join_criteria = None
|
|
201
|
+
join_type = self.__join_type()
|
|
202
|
+
if join_type != JoinType.CROSS:
|
|
203
|
+
join_condition_expr = self.__build_condition()
|
|
204
|
+
if isinstance(join_condition_expr, bool):
|
|
205
|
+
join_condition_expr = PyLegendBoolean(PyLegendBooleanLiteralExpression(join_condition_expr)) # pragma: no cover # noqa: E501
|
|
206
|
+
join_sql_expr = join_condition_expr.to_sql_expression(
|
|
207
|
+
{
|
|
208
|
+
"left": create_sub_query(left_query, config, "left"),
|
|
209
|
+
"right": create_sub_query(right_query, config, "right"),
|
|
210
|
+
},
|
|
211
|
+
config
|
|
212
|
+
)
|
|
213
|
+
join_criteria = JoinOn(expression=join_sql_expr)
|
|
214
|
+
|
|
215
|
+
left_alias = db_extension.quote_identifier("left")
|
|
216
|
+
right_alias = db_extension.quote_identifier("right")
|
|
217
|
+
|
|
218
|
+
left_original = {c.get_name(): c for c in self.__base_frame.columns()}
|
|
219
|
+
right_original = {c.get_name(): c for c in self.__other_frame.columns()}
|
|
220
|
+
key_pairs = self.__derive_key_pairs()
|
|
221
|
+
same_name_keys = {left_key for left_key, right_key in key_pairs if left_key == right_key}
|
|
222
|
+
|
|
223
|
+
select_items: PyLegendList[SelectItem] = []
|
|
224
|
+
|
|
225
|
+
left_cols_set = set(left_original.keys())
|
|
226
|
+
right_cols_set = set(right_original.keys())
|
|
227
|
+
overlapping = (left_cols_set & right_cols_set) - same_name_keys
|
|
228
|
+
|
|
229
|
+
# Left select items
|
|
230
|
+
for c in self.__base_frame.columns():
|
|
231
|
+
orig = c.get_name()
|
|
232
|
+
out_name = orig + self.__suffixes[0] if orig in overlapping else orig # type: ignore
|
|
233
|
+
q_out = db_extension.quote_identifier(out_name)
|
|
234
|
+
q_in = db_extension.quote_identifier(orig)
|
|
235
|
+
select_items.append(
|
|
236
|
+
SingleColumn(q_out, QualifiedNameReference(QualifiedName(parts=[left_alias, q_in])))
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
# Right select items
|
|
240
|
+
for c in self.__other_frame.columns():
|
|
241
|
+
orig = c.get_name()
|
|
242
|
+
if orig in same_name_keys:
|
|
243
|
+
continue
|
|
244
|
+
|
|
245
|
+
out_name = orig + self.__suffixes[1] if orig in overlapping else orig # type: ignore
|
|
246
|
+
q_out = db_extension.quote_identifier(out_name)
|
|
247
|
+
q_in = db_extension.quote_identifier(orig)
|
|
248
|
+
select_items.append(
|
|
249
|
+
SingleColumn(q_out, QualifiedNameReference(QualifiedName(parts=[right_alias, q_in])))
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
join_spec = QuerySpecification(
|
|
253
|
+
select=Select(selectItems=select_items, distinct=False),
|
|
254
|
+
from_=[
|
|
255
|
+
Join(
|
|
256
|
+
type_=self.__join_type(),
|
|
257
|
+
left=AliasedRelation(
|
|
258
|
+
relation=TableSubquery(Query(queryBody=left_query, limit=None, offset=None, orderBy=[])),
|
|
259
|
+
alias=left_alias,
|
|
260
|
+
columnNames=extract_columns_for_subquery(left_query)
|
|
261
|
+
),
|
|
262
|
+
right=AliasedRelation(
|
|
263
|
+
relation=TableSubquery(Query(queryBody=right_query, limit=None, offset=None, orderBy=[])),
|
|
264
|
+
alias=right_alias,
|
|
265
|
+
columnNames=extract_columns_for_subquery(right_query)
|
|
266
|
+
),
|
|
267
|
+
criteria=join_criteria
|
|
268
|
+
)
|
|
269
|
+
],
|
|
270
|
+
where=None,
|
|
271
|
+
groupBy=[],
|
|
272
|
+
having=None,
|
|
273
|
+
orderBy=[],
|
|
274
|
+
limit=None,
|
|
275
|
+
offset=None
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
return create_sub_query(join_spec, config, "root")
|
|
279
|
+
|
|
280
|
+
def to_pure(self, config: FrameToPureConfig) -> str:
|
|
281
|
+
how_lower = self.__how.lower() # type: ignore
|
|
282
|
+
if how_lower == "inner":
|
|
283
|
+
join_kind = "INNER"
|
|
284
|
+
elif how_lower == "left":
|
|
285
|
+
join_kind = "LEFT"
|
|
286
|
+
elif how_lower == "right":
|
|
287
|
+
join_kind = "RIGHT"
|
|
288
|
+
elif how_lower == "outer":
|
|
289
|
+
join_kind = "FULL"
|
|
290
|
+
elif how_lower == "cross":
|
|
291
|
+
join_kind = "INNER"
|
|
292
|
+
|
|
293
|
+
# Resolve key pairs
|
|
294
|
+
key_pairs = self.__derive_key_pairs()
|
|
295
|
+
|
|
296
|
+
left_cols = [c.get_name() for c in self.__base_frame.columns()]
|
|
297
|
+
right_cols = [c.get_name() for c in self.__other_frame.columns()]
|
|
298
|
+
|
|
299
|
+
# Suffix handling for overlapping non-key columns
|
|
300
|
+
s = list(self.__suffixes) # type: ignore
|
|
301
|
+
left_suf, right_suf = s[0], s[1]
|
|
302
|
+
|
|
303
|
+
left_col_set = set(left_cols)
|
|
304
|
+
right_col_set = set(right_cols)
|
|
305
|
+
overlapping = left_col_set & right_col_set
|
|
306
|
+
|
|
307
|
+
# Overlapping join keys (same name) need temporary rename on right to allow join
|
|
308
|
+
identical_key_names = {
|
|
309
|
+
lk for (lk, rk) in key_pairs if lk == rk
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
left_rename_map = {}
|
|
313
|
+
right_rename_map = {}
|
|
314
|
+
|
|
315
|
+
# Non-key overlapping columns get suffixes
|
|
316
|
+
for col in overlapping:
|
|
317
|
+
if col in identical_key_names:
|
|
318
|
+
continue
|
|
319
|
+
|
|
320
|
+
left_rename_map[col] = col + left_suf # type: ignore
|
|
321
|
+
right_rename_map[col] = col + right_suf # type: ignore
|
|
322
|
+
|
|
323
|
+
# Temporary rename for identical key names on right
|
|
324
|
+
temp_right_key_map = {}
|
|
325
|
+
for k in identical_key_names:
|
|
326
|
+
temp_name = k + "__right_key_tmp"
|
|
327
|
+
temp_right_key_map[k] = temp_name
|
|
328
|
+
|
|
329
|
+
# Rename
|
|
330
|
+
left_frame = (self.__base_frame.rename(columns=left_rename_map, errors="raise")
|
|
331
|
+
if left_rename_map else self.__base_frame)
|
|
332
|
+
|
|
333
|
+
right_map = {**right_rename_map, **temp_right_key_map} if (right_rename_map or temp_right_key_map) else None
|
|
334
|
+
right_frame = (self.__other_frame.rename(columns=right_map, errors="raise")
|
|
335
|
+
if right_map else self.__other_frame)
|
|
336
|
+
|
|
337
|
+
# Build join condition expression
|
|
338
|
+
if how_lower != "cross":
|
|
339
|
+
left_row = PandasApiTdsRow.from_tds_frame("l", left_frame)
|
|
340
|
+
right_row = PandasApiTdsRow.from_tds_frame("r", right_frame)
|
|
341
|
+
|
|
342
|
+
expr = None
|
|
343
|
+
for l_key, r_key in key_pairs:
|
|
344
|
+
l_eff = left_rename_map.get(l_key, l_key)
|
|
345
|
+
r_eff = right_map.get(r_key, r_key) # type: ignore
|
|
346
|
+
part = (left_row[l_eff] == right_row[r_eff])
|
|
347
|
+
expr = part if expr is None else (expr & part)
|
|
348
|
+
|
|
349
|
+
if not isinstance(expr, PyLegendPrimitive):
|
|
350
|
+
expr = convert_literal_to_literal_expression(expr) # type: ignore # pragma: no cover
|
|
351
|
+
cond_str = expr.to_pure_expression(config.push_indent(2)) # type: ignore
|
|
352
|
+
else:
|
|
353
|
+
cond_str = "1==1"
|
|
354
|
+
|
|
355
|
+
left_pure = left_frame.to_pure(config) # type: ignore
|
|
356
|
+
right_pure = right_frame.to_pure(config.push_indent(2)) # type: ignore
|
|
357
|
+
|
|
358
|
+
join_expr = (
|
|
359
|
+
f"{left_pure}{config.separator(1)}"
|
|
360
|
+
f"->join({config.separator(2)}"
|
|
361
|
+
f"{right_pure},{config.separator(2, True)}"
|
|
362
|
+
f"JoinKind.{join_kind},{config.separator(2, True)}"
|
|
363
|
+
f"{generate_pure_lambda('l, r', cond_str)}{config.separator(1)})"
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
# Only project if temporary right key renames exist
|
|
367
|
+
if temp_right_key_map:
|
|
368
|
+
final_cols = []
|
|
369
|
+
|
|
370
|
+
for c in left_cols:
|
|
371
|
+
if (c in overlapping and c not in identical_key_names):
|
|
372
|
+
final_cols.append(c + left_suf) # type: ignore
|
|
373
|
+
else:
|
|
374
|
+
final_cols.append(c)
|
|
375
|
+
|
|
376
|
+
for c in right_cols:
|
|
377
|
+
if c in temp_right_key_map:
|
|
378
|
+
continue
|
|
379
|
+
if (c in overlapping and c not in identical_key_names):
|
|
380
|
+
final_cols.append(c + right_suf) # type: ignore
|
|
381
|
+
else:
|
|
382
|
+
final_cols.append(c)
|
|
383
|
+
|
|
384
|
+
project_items = [f"{col}:x|$x.{col}" for col in final_cols]
|
|
385
|
+
project_body = ", ".join(project_items)
|
|
386
|
+
join_expr = (
|
|
387
|
+
f"{join_expr}{config.separator(1)}"
|
|
388
|
+
f"->project({config.separator(2)}~[{project_body}]{config.separator(1)})"
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
return join_expr
|
|
392
|
+
|
|
393
|
+
def base_frame(self) -> PandasApiBaseTdsFrame:
|
|
394
|
+
return self.__base_frame
|
|
395
|
+
|
|
396
|
+
def tds_frame_parameters(self) -> PyLegendList["PandasApiBaseTdsFrame"]:
|
|
397
|
+
return [self.__other_frame]
|
|
398
|
+
|
|
399
|
+
def calculate_columns(self) -> PyLegendSequence["TdsColumn"]:
|
|
400
|
+
key_pairs = self.__derive_key_pairs()
|
|
401
|
+
left_keys_same_name = {left_key for left_key, right_key in key_pairs if left_key == right_key}
|
|
402
|
+
left_cols = [c.get_name() for c in self.__base_frame.columns()]
|
|
403
|
+
right_cols = [c.get_name() for c in self.__other_frame.columns()]
|
|
404
|
+
|
|
405
|
+
overlapping = (set(left_cols) & set(right_cols)) - left_keys_same_name
|
|
406
|
+
|
|
407
|
+
# Build left columns (apply suffix to overlapping non-key)
|
|
408
|
+
result_cols: PyLegendSequence["TdsColumn"] = []
|
|
409
|
+
for c in self.__base_frame.columns():
|
|
410
|
+
name = c.get_name()
|
|
411
|
+
if name in overlapping:
|
|
412
|
+
result_cols.append(c.copy_with_changed_name(name + self.__suffixes[0])) # type: ignore
|
|
413
|
+
else:
|
|
414
|
+
result_cols.append(c.copy()) # type: ignore
|
|
415
|
+
|
|
416
|
+
# Build right columns (skip same-name keys; apply suffix to overlapping non-key)
|
|
417
|
+
for c in self.__other_frame.columns():
|
|
418
|
+
name = c.get_name()
|
|
419
|
+
if any(name == left_key and left_key == right_key for left_key, right_key in key_pairs):
|
|
420
|
+
continue
|
|
421
|
+
|
|
422
|
+
if name in overlapping:
|
|
423
|
+
result_cols.append(c.copy_with_changed_name(name + self.__suffixes[1])) # type: ignore
|
|
424
|
+
else:
|
|
425
|
+
result_cols.append(c.copy()) # type: ignore
|
|
426
|
+
|
|
427
|
+
# Validate no duplicates
|
|
428
|
+
names = [c.get_name() for c in result_cols]
|
|
429
|
+
if len(names) != len(set(names)):
|
|
430
|
+
raise ValueError("Resulting merged columns contain duplicates after suffix application")
|
|
431
|
+
|
|
432
|
+
if self.__sort:
|
|
433
|
+
for lk, rk in key_pairs:
|
|
434
|
+
left_out = (lk + self.__suffixes[0]) if (lk in overlapping) else lk # type: ignore
|
|
435
|
+
self.__sortkeys.append(left_out)
|
|
436
|
+
|
|
437
|
+
if rk != lk:
|
|
438
|
+
right_out = (rk + self.__suffixes[1]) if (rk in overlapping) else rk # type: ignore
|
|
439
|
+
# right identical-name keys are skipped
|
|
440
|
+
self.__sortkeys.append(right_out)
|
|
441
|
+
|
|
442
|
+
return result_cols
|
|
443
|
+
|
|
444
|
+
def validate(self) -> bool:
|
|
445
|
+
# Frame type validation
|
|
446
|
+
if not isinstance(self.__other_frame, PandasApiTdsFrame):
|
|
447
|
+
raise TypeError(f"Can only merge TdsFrame objects, a {type(self.__other_frame)} was passed")
|
|
448
|
+
|
|
449
|
+
# Same frame not supported
|
|
450
|
+
if self.__base_frame is self.__other_frame:
|
|
451
|
+
raise NotImplementedError("Merging the same TdsFrame is not supported yet")
|
|
452
|
+
|
|
453
|
+
# how
|
|
454
|
+
if not isinstance(self.__how, str):
|
|
455
|
+
raise TypeError(f"'how' must be str, got {type(self.__how)}")
|
|
456
|
+
|
|
457
|
+
if self.__how.lower() == "cross":
|
|
458
|
+
if any(v is not None for v in (self.__on, self.__left_on, self.__right_on)):
|
|
459
|
+
raise ValueError("Can not pass on, right_on, left_on for how='cross'")
|
|
460
|
+
|
|
461
|
+
# key parameters: on / left_on / right_on
|
|
462
|
+
def _validate_keys_param(param_name: str, value: PyLegendUnion[str, PyLegendSequence[str], None]) -> None:
|
|
463
|
+
if value is None:
|
|
464
|
+
return
|
|
465
|
+
if isinstance(value, str):
|
|
466
|
+
return
|
|
467
|
+
if isinstance(value, (list, tuple)):
|
|
468
|
+
if not all(isinstance(v, str) for v in value):
|
|
469
|
+
raise TypeError(f"'{param_name}' must contain only str elements")
|
|
470
|
+
return
|
|
471
|
+
raise TypeError(
|
|
472
|
+
f"Passing '{param_name}' as a {type(value)} is not supported. "
|
|
473
|
+
f"Provide '{param_name}' as a tuple instead."
|
|
474
|
+
)
|
|
475
|
+
|
|
476
|
+
_validate_keys_param("on", self.__on)
|
|
477
|
+
_validate_keys_param("left_on", self.__left_on)
|
|
478
|
+
_validate_keys_param("right_on", self.__right_on)
|
|
479
|
+
|
|
480
|
+
# Suffix validation
|
|
481
|
+
if not isinstance(self.__suffixes, (tuple, list)):
|
|
482
|
+
raise TypeError(
|
|
483
|
+
f"Passing 'suffixes' as {type(self.__suffixes)}, is not supported. "
|
|
484
|
+
"Provide 'suffixes' as a tuple instead."
|
|
485
|
+
)
|
|
486
|
+
for s in self.__suffixes:
|
|
487
|
+
if s is not None and not isinstance(s, str):
|
|
488
|
+
raise TypeError("'suffixes' elements must be str or None")
|
|
489
|
+
if len(self.__suffixes) != 2:
|
|
490
|
+
raise ValueError("too many values to unpack (expected 2)")
|
|
491
|
+
|
|
492
|
+
# Sort
|
|
493
|
+
if self.__sort is not None and not isinstance(self.__sort, (bool, PyLegendBoolean)):
|
|
494
|
+
raise TypeError(f"Sort parameter must be bool, got {type(self.__sort)}")
|
|
495
|
+
|
|
496
|
+
# Unsupported parameters
|
|
497
|
+
if self.__left_index or self.__right_index:
|
|
498
|
+
raise NotImplementedError("Merging on index is not supported yet in PandasApi merge function")
|
|
499
|
+
|
|
500
|
+
if self.__indicator:
|
|
501
|
+
raise NotImplementedError("Indicator parameter is not supported yet in PandasApi merge function")
|
|
502
|
+
|
|
503
|
+
if self.__validate:
|
|
504
|
+
raise NotImplementedError("Validate parameter is not supported yet in PandasApi merge function")
|
|
505
|
+
|
|
506
|
+
self.__join_type() # runs how validation
|
|
507
|
+
self.__normalize_suffixes() # runs suffixes validation
|
|
508
|
+
|
|
509
|
+
key_pairs = self.__derive_key_pairs() # runs key validations
|
|
510
|
+
if not key_pairs and self.__how.lower() != "cross":
|
|
511
|
+
raise ValueError("No merge keys resolved. Specify 'on' or 'left_on'/'right_on', or ensure common columns.")
|
|
512
|
+
|
|
513
|
+
return True
|