tdfs4ds 0.2.4.31__py3-none-any.whl → 0.2.4.32__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.
@@ -1,239 +1,524 @@
1
+ import datetime
2
+ import numpy as np # Needed for np.datetime64 handling in get_date_in_the_past
1
3
  import teradataml as tdml
2
4
  import tdfs4ds
3
- import datetime
5
+ from tdfs4ds import logger
4
6
 
5
7
 
6
8
  def get_hidden_table_name(table_name):
7
- return table_name + '_HIDDEN'
9
+ """
10
+ Return the backing 'hidden' table name for a public view/table.
11
+
12
+ Args:
13
+ table_name (str): Public-facing table/view name.
14
+
15
+ Returns:
16
+ str: The corresponding hidden table name (suffix '_HIDDEN').
17
+ """
18
+ return table_name + "_HIDDEN"
8
19
 
9
20
 
10
21
  class FilterManager:
11
22
  """
12
- Manages dynamic filtering on a database table by creating and maintaining a view based on specified filter criteria.
23
+ Manage dynamic, filter-driven views over a Teradata table.
13
24
 
14
- This class enables dynamic filtering of a Teradata database table, providing methods to create, update, and manage
15
- a view that represents filtered data based on a specific filter ID. It facilitates loading new filters, updating
16
- existing ones, and managing time-based filtering if applicable.
25
+ This class maintains a hidden table that stores one or more *filters* (one row
26
+ per filter definition) and exposes a public view whose SELECT projects the
27
+ columns from the hidden table for the currently-active filter ID. You can load
28
+ new filters, switch which filter the view points at, prune older filters, and
29
+ (optionally) include a time dimension via a `BUSINESS_DATE` column.
17
30
 
18
31
  Attributes:
19
- schema_name (str): The schema in the database containing the table and view.
20
- table_name (str): The underlying table in the schema holding the raw data for filtering.
21
- view_name (str): The view representing filtered data based on current filter criteria.
22
- filter_id_name (str): The column identifying different filters. Defaults to 'filter_id'.
23
- nb_filters (int): The count of filters currently defined in the table, updated with filter changes.
24
- col_names (list): List of column names in the table excluding the filter ID and time columns.
25
- time_filtering (bool): Indicates if time-based filtering is enabled based on a 'BUSINESS_DATE' column.
32
+ schema_name (str): Database schema that contains the hidden table and public view.
33
+ table_name (str): Hidden table name where filter rows are stored.
34
+ view_name (str): Public view name pointing at the currently active filter row.
35
+ filter_id_name (str): Column name containing the filter identifier (default 'filter_id').
36
+ nb_filters (int | None): Number of filters currently stored (max filter_id). Populated when objects exist.
37
+ col_names (list[str] | None): Columns projected by the view (excludes filter-id and time column).
38
+ time_filtering (bool | None): Whether a `BUSINESS_DATE` column is present/used.
26
39
  """
27
40
 
28
- def __init__(self, table_name, schema_name, filter_id_name='filter_id', time_column = None):
41
+ def __init__(self, table_name, schema_name, filter_id_name="filter_id", time_column=None):
29
42
  """
30
- Initializes the FilterManager for managing filtered views.
43
+ Initialize the FilterManager.
31
44
 
32
- Checks for the existence of the specified table in the schema. If the table exists, the FilterManager
33
- initializes attributes for the column names, filter count, and time-based filtering. If not, provisions
34
- for table creation are set up.
45
+ If the hidden table/view already exist, metadata (column names, maximum
46
+ filter id, and time filtering status) are detected and cached. If they do
47
+ not exist yet, attributes are initialized but no objects are created until
48
+ `load_filter()` is called.
35
49
 
36
50
  Args:
37
- table_name (str): Name of the table to manage filters for.
38
- schema_name (str): Name of the schema where the table is located.
39
- filter_id_name (str, optional): Column name used to identify filters. Defaults to 'filter_id'.
40
- time_column (str, optional): Optional time column name for time-based filtering.
41
- """
42
- self.schema_name = schema_name
43
- self.table_name = get_hidden_table_name(table_name)
44
- self.view_name = table_name
51
+ table_name (str): Public view name to maintain.
52
+ schema_name (str): Schema where the view and hidden table live.
53
+ filter_id_name (str, optional): Name of the filter id column. Defaults to 'filter_id'.
54
+ time_column (str, optional): If provided, indicates the source column
55
+ in incoming DataFrames to copy into `BUSINESS_DATE` during `load_filter()`.
56
+ (Note: this parameter is remembered but the actual `BUSINESS_DATE`
57
+ column is only created/used when `load_filter(time_column=...)` is called.)
58
+ """
59
+ self.schema_name = schema_name
60
+ self.table_name = get_hidden_table_name(table_name)
61
+ self.view_name = table_name
45
62
  self.filter_id_name = filter_id_name
46
- self.nb_filters = None
47
- self.col_names = None
63
+ self.nb_filters = None
64
+ self.col_names = None
48
65
  self.time_filtering = None
66
+ self._init_time_column = time_column # remember user hint for later `load_filter` calls
67
+
68
+ logger.debug(
69
+ "Initializing FilterManager",
70
+ extra={
71
+ "schema_name": self.schema_name,
72
+ "view_name": self.view_name,
73
+ "table_name": self.table_name,
74
+ "filter_id_name": self.filter_id_name,
75
+ },
76
+ )
49
77
 
50
78
  if self._exists():
51
- if tdfs4ds.DEBUG_MODE:
52
- print('filter exists: ',[x for x in tdml.db_list_tables(schema_name=self.schema_name).TableName.values if
53
- x.lower().replace('"', '') == self.view_name.lower()])
54
- print('schema_name:', self.schema_name)
55
- print('table_name:', self.table_name)
79
+ logger.info(
80
+ "Existing filter artifacts detected.",
81
+ extra={"schema_name": self.schema_name, "view_name": self.view_name, "table_name": self.table_name},
82
+ )
56
83
  df = tdml.DataFrame(tdml.in_schema(self.schema_name, self.table_name))
84
+ # First column is assumed to be the filter id
57
85
  self.filter_id_name = df.columns[0]
58
- self.nb_filters = tdml.execute_sql(
59
- f"SEL MAX({self.filter_id_name}) AS nb_filters FROM {self.schema_name}.{self.table_name}").fetchall()[
60
- 0][0]
86
+ self.nb_filters = tdml.execute_sql(
87
+ f"SEL MAX({self.filter_id_name}) AS nb_filters FROM {self.schema_name}.{self.table_name}"
88
+ ).fetchall()[0][0]
61
89
  self.time_filtering = self._istimefiltering()
62
- if self.time_filtering:
63
- self.col_names = df.columns[2::]
64
- else:
65
- self.col_names = df.columns[1::]
90
+ self.col_names = df.columns[2:] if self.time_filtering else df.columns[1:]
91
+ logger.debug(
92
+ "Detected existing configuration.",
93
+ extra={
94
+ "filter_id_name": self.filter_id_name,
95
+ "nb_filters": self.nb_filters,
96
+ "time_filtering": self.time_filtering,
97
+ "col_names": list(self.col_names),
98
+ },
99
+ )
100
+ else:
101
+ logger.info(
102
+ "No existing filter artifacts found; will be created by load_filter().",
103
+ extra={"schema_name": self.schema_name, "view_name": self.view_name, "table_name": self.table_name},
104
+ )
66
105
 
67
106
  def _istimefiltering(self):
68
- """Check if the table has a 'BUSINESS_DATE' column for time-based filtering."""
107
+ """
108
+ Determine if the hidden table includes a `BUSINESS_DATE` column.
109
+
110
+ Returns:
111
+ bool: True if the hidden table contains `BUSINESS_DATE`, else False.
112
+ """
69
113
  df = tdml.DataFrame(tdml.in_schema(self.schema_name, self.table_name))
70
- return 'BUSINESS_DATE' in df.columns
114
+ has_time = "BUSINESS_DATE" in df.columns
115
+ logger.debug("Time filtering detected: %s", has_time)
116
+ return has_time
71
117
 
72
118
  def _exists(self):
73
- """Check if both table and view exist."""
74
- existing_tables = [x.lower().replace('"', '') for x in
75
- tdml.db_list_tables(schema_name=self.schema_name).TableName.values]
76
- return self.view_name.lower() in existing_tables or self.table_name.lower() in existing_tables
77
- def load_filter(self, df, primary_index=None, time_column = None):
78
119
  """
79
- Loads a new filter into the table and updates the view to reflect this filter.
120
+ Check if either the public view or hidden table already exist in the schema.
121
+
122
+ Returns:
123
+ bool: True if the hidden table or view exists, else False.
124
+ """
125
+ existing_tables = [
126
+ x.lower().replace('"', "") for x in tdml.db_list_tables(schema_name=self.schema_name).TableName.values
127
+ ]
128
+ exists = self.view_name.lower() in existing_tables or self.table_name.lower() in existing_tables
129
+ logger.debug("Existence check", extra={"exists": exists, "objects": existing_tables})
130
+ return exists
131
+
132
+ def load_filter(self, df, primary_index=None, time_column=None):
133
+ """
134
+ Load a new filter set into the hidden table and (re)point the public view at filter_id=1.
80
135
 
81
- This method takes a DataFrame as input, assigns filter IDs to each row, and updates or replaces the table
82
- and view to reflect the new filter configuration. If `time_column` is specified and present in `df`,
83
- it will be used in time-based filtering logic. Raises a ValueError if `time_column` is specified but not found in `df`.
136
+ Each row in `df` is assigned a deterministic `filter_id` based on ROW_NUMBER() over the
137
+ ordered set of its columns (plus `BUSINESS_DATE` when time filtering is enabled). If
138
+ `time_column` is provided, values from that column are copied into `BUSINESS_DATE` and the
139
+ view will include that time dimension.
84
140
 
85
141
  Args:
86
- df (DataFrame): DataFrame containing the new filter configuration.
87
- primary_index (list, optional): List of primary index columns for the table. Defaults to `['filter_id']`.
88
- time_column (str, optional): Column name used for time-based filtering, if applicable.
142
+ df (DataFrame): Incoming filter definitions (one row per filter).
143
+ primary_index (list[str], optional): Primary index columns for the hidden table.
144
+ Defaults to ['filter_id'] when omitted.
145
+ time_column (str, optional): Name of the time column in `df` to map into `BUSINESS_DATE`.
146
+ If provided, time-based filtering is enabled.
147
+
148
+ Raises:
149
+ ValueError: If `time_column` is provided but not present in `df`.
89
150
  """
151
+ logger.info("Loading filters", extra={"rows": len(df), "time_column": time_column})
90
152
 
91
153
  if time_column and time_column not in df.columns:
154
+ logger.error("Specified time_column not found in DataFrame.", extra={"time_column": time_column})
92
155
  raise ValueError(f"Specified time_column '{time_column}' not found in DataFrame columns.")
93
156
 
157
+ # Determine projection and ordering columns
94
158
  if time_column is None:
159
+ self.time_filtering = False
95
160
  self.col_names = df.columns
96
- all_columns = ','.join(df.columns)
97
- collect_stats = ','.join([f'COLUMN ({c}) \n' for c in df.columns])
161
+ all_columns = ",".join(df.columns)
162
+ collect_stats = ",".join([f"COLUMN ({c})" for c in df.columns])
98
163
  else:
99
164
  self.time_filtering = True
100
- # check if time_colum is part of the column
101
165
  self.col_names = [c for c in df.columns if c != time_column]
102
- all_columns = ','.join(['BUSINESS_DATE'] + [c for c in df.columns if c != time_column])
103
- collect_stats = ','.join([f'COLUMN ({c})' for c in ['BUSINESS_DATE'] + [c for c in df.columns if c != time_column]])
104
-
105
-
166
+ all_columns = ",".join(["BUSINESS_DATE"] + self.col_names)
167
+ collect_stats = ",".join([f"COLUMN ({c})" for c in ["BUSINESS_DATE"] + self.col_names])
106
168
 
169
+ logger.debug(
170
+ "Computed load_filter columns",
171
+ extra={"time_filtering": self.time_filtering, "col_names": list(self.col_names), "all_columns": all_columns},
172
+ )
107
173
 
174
+ # Build the filter rows with an ordered ROW_NUMBER()
108
175
  if time_column is None:
109
- df_filter = df.assign(**{
110
- self.filter_id_name: tdml.sqlalchemy.literal_column(
111
- f"ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY {all_columns})", tdml.BIGINT())}
112
- )[['filter_id'] + df.columns]
113
-
176
+ df_filter = df.assign(
177
+ **{
178
+ self.filter_id_name: tdml.sqlalchemy.literal_column(
179
+ f"ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY {all_columns})", tdml.BIGINT()
180
+ )
181
+ }
182
+ )[[self.filter_id_name] + list(df.columns)]
114
183
  else:
115
- df_filter = df.assign(**{
116
- self.filter_id_name: tdml.sqlalchemy.literal_column(
117
- f"ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY {all_columns})", tdml.BIGINT()),
118
- 'BUSINESS_DATE' : df[time_column]
119
- })[['filter_id'] + ['BUSINESS_DATE'] + [c for c in df.columns if c != time_column]]
120
-
121
-
184
+ df_filter = df.assign(
185
+ **{
186
+ self.filter_id_name: tdml.sqlalchemy.literal_column(
187
+ f"ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY {all_columns})", tdml.BIGINT()
188
+ ),
189
+ "BUSINESS_DATE": df[time_column],
190
+ }
191
+ )[[self.filter_id_name, "BUSINESS_DATE"] + self.col_names]
192
+
193
+ # Persist to hidden table
122
194
  if primary_index is None:
123
- df_filter.to_sql(
124
- table_name = self.table_name,
125
- schema_name = self.schema_name,
126
- if_exists = 'replace',
127
- primary_index = ['filter_id'])
128
- else:
129
- df_filter.to_sql(table_name=self.table_name, schema_name=self.schema_name, if_exists='replace',
130
- primary_index=primary_index)
131
-
132
- query = f"""
195
+ primary_index = [self.filter_id_name]
196
+
197
+ logger.debug("Writing hidden table", extra={"primary_index": primary_index})
198
+ df_filter.to_sql(
199
+ table_name=self.table_name,
200
+ schema_name=self.schema_name,
201
+ if_exists="replace",
202
+ primary_index=primary_index,
203
+ )
204
+
205
+ # Create/replace public view with filter_id = 1
206
+ view_sql = f"""
133
207
  REPLACE VIEW {self.schema_name}.{self.view_name} AS
134
208
  SEL {all_columns}
135
209
  FROM {self.schema_name}.{self.table_name}
136
210
  WHERE {self.filter_id_name} = 1
137
211
  """
212
+ logger.debug("Replacing view for filter_id=1")
213
+ tdml.execute_sql(view_sql)
138
214
 
139
- # Collect stats
140
-
141
- query_collect_stats = f"""
215
+ # Collect stats to help the optimizer
216
+ stats_sql = f"""
142
217
  COLLECT STATISTICS USING NO SAMPLE AND NO THRESHOLD
143
- COLUMN (filter_id)
218
+ COLUMN ({self.filter_id_name})
144
219
  , {collect_stats}
145
220
  ON {self.schema_name}.{self.table_name}
146
221
  """
147
- tdml.execute_sql(query_collect_stats)
148
- tdml.execute_sql(query)
222
+ logger.debug("Collecting statistics on hidden table")
223
+ tdml.execute_sql(stats_sql)
149
224
 
150
225
  self.nb_filters = tdml.execute_sql(
151
- f"SEL MAX({self.filter_id_name}) AS nb_filters FROM {self.schema_name}.{self.table_name}").fetchall()[0][0]
226
+ f"SEL MAX({self.filter_id_name}) AS nb_filters FROM {self.schema_name}.{self.table_name}"
227
+ ).fetchall()[0][0]
228
+ logger.info("Filters loaded", extra={"nb_filters": self.nb_filters})
152
229
 
153
230
  def _drop(self):
154
231
  """
155
- Drops the view and the table from the database if they exist.
232
+ Drop the public view and (optionally) the hidden table.
156
233
 
157
- This method is used to clean up the database by removing the managed view and table. It checks for the existence of the table and view before attempting to drop them.
234
+ If this manager does not own the hidden table (default), only the view is dropped.
158
235
  """
159
- # Drop the table if it exists
160
- if self._exists():
161
- tdml.db_drop_view(schema_name=self.schema_name, table_name=self.table_view)
162
- tdml.db_drop_table(schema_name=self.schema_name, table_name=self.table_name)
236
+ # Drop the view (in our schema)
237
+ existing = [x.lower().replace('"', "") for x in tdml.db_list_tables(schema_name=self.schema_name).TableName.values]
238
+ if self.view_name.lower() in existing:
239
+ logger.warning("Dropping view.", extra={"schema_name": self.schema_name, "view_name": self.view_name})
240
+ tdml.db_drop_view(schema_name=self.schema_name, table_name=self.view_name)
241
+ else:
242
+ logger.info("View not found; nothing to drop.", extra={"schema_name": self.schema_name, "view_name": self.view_name})
243
+
244
+ # Drop the hidden table only if we own it
245
+ if getattr(self, "_owns_hidden", False):
246
+ schema_tbl = getattr(self, "schema_name_for_table", self.schema_name)
247
+ logger.warning(
248
+ "Dropping hidden table (ownership acknowledged).",
249
+ extra={"schema_name": schema_tbl, "table_name": self.table_name},
250
+ )
251
+ tdml.db_drop_table(schema_name=schema_tbl, table_name=self.table_name)
252
+ else:
253
+ logger.info("Hidden table not dropped (not owned).")
254
+
163
255
 
164
256
  def update(self, filter_id):
165
257
  """
166
- Updates the view to apply a new filter based on the provided filter ID.
258
+ Repoint the public view to a different filter id.
167
259
 
168
260
  Args:
169
- filter_id (int): The ID of the filter to apply. The view will be updated to only show data that matches this filter ID.
261
+ filter_id (int): Target filter id to apply.
262
+
263
+ Raises:
264
+ ValueError: If filter artifacts do not exist yet.
170
265
  """
266
+ logger.info("Updating active filter", extra={"filter_id": filter_id})
267
+
171
268
  if not self._exists():
172
- raise ValueError(f"The filter has not be initialized with load_filter or has been deleted.")
269
+ logger.error("Filter artifacts not initialized.")
270
+ raise ValueError("The filter has not been initialized with load_filter() or has been deleted.")
173
271
 
174
272
  if self.time_filtering:
175
- query = f"""
176
- REPLACE VIEW {self.schema_name}.{self.view_name} AS
177
- SEL {','.join(['BUSINESS_DATE']+self.col_names)}
178
- FROM {self.schema_name}.{self.table_name}
179
- WHERE {self.filter_id_name} = {filter_id}
180
- """
181
-
273
+ select_cols = ",".join(["BUSINESS_DATE"] + list(self.col_names))
182
274
  else:
183
- query = f"""
184
- REPLACE VIEW {self.schema_name}.{self.view_name} AS
185
- SEL {','.join(self.col_names)}
186
- FROM {self.schema_name}.{self.table_name}
187
- WHERE {self.filter_id_name} = {filter_id}
188
- """
189
-
190
- if tdfs4ds.DEBUG_MODE:
191
- print(query)
275
+ select_cols = ",".join(self.col_names)
276
+
277
+ query = f"""
278
+ REPLACE VIEW {self.schema_name}.{self.view_name} AS
279
+ SEL {select_cols}
280
+ FROM {self.schema_name}.{self.table_name}
281
+ WHERE {self.filter_id_name} = {filter_id}
282
+ """
283
+ logger.debug("Replacing view with new filter", extra={"query": query})
192
284
  tdml.execute_sql(query)
193
285
 
194
286
  def display(self):
195
287
  """
196
- Retrieves the current data from the view as a DataFrame.
288
+ Retrieve the current view contents as a `teradataml.DataFrame`.
197
289
 
198
290
  Returns:
199
- DataFrame: The current data visible through the view, filtered by the active filter ID.
291
+ teradataml.DataFrame: Rows projected by the public view (current filter).
200
292
  """
293
+ logger.debug("Fetching current view contents")
201
294
  return tdml.DataFrame(tdml.in_schema(self.schema_name, self.view_name))
202
295
 
203
296
  def get_all_filters(self):
297
+ """
298
+ Retrieve all filter rows from the hidden table.
299
+
300
+ Returns:
301
+ teradataml.DataFrame: Full set of stored filters.
302
+ """
303
+ logger.debug("Fetching all filters from hidden table")
204
304
  return tdml.DataFrame(tdml.in_schema(self.schema_name, self.table_name))
205
305
 
206
306
  def get_date_in_the_past(self):
207
307
  """
208
- Retrieves the earliest date and time value from the table.
308
+ Return the earliest business date/time from the *current view*.
309
+
310
+ The method reads the first `BUSINESS_DATE` value from the current view
311
+ and normalizes it to a `%Y-%m-%d %H:%M:%S` string. Requires that time
312
+ filtering is enabled.
209
313
 
210
314
  Returns:
211
- str: The earliest date and time value as a formatted string ('YYYY-MM-DD HH:MM:SS').
315
+ str: Earliest datetime as formatted string ('YYYY-MM-DD HH:MM:SS').
316
+
317
+ Raises:
318
+ ValueError: If time-based filtering is not enabled.
212
319
  """
320
+ logger.debug("Computing earliest BUSINESS_DATE from current view")
213
321
 
214
- if self._istimefiltering() == False:
215
- raise ValueError(f"The filter manager is not filtering on time.")
322
+ if not self._istimefiltering():
323
+ logger.error("Time filtering requested but not enabled.")
324
+ raise ValueError("The filter manager is not filtering on time.")
216
325
 
217
- # '9999-01-01 00:00:00'
218
326
  date_obj = self.display().to_pandas().reset_index().BUSINESS_DATE.values[0]
219
327
 
220
328
  if isinstance(date_obj, datetime.datetime):
221
- # print("temp is a datetime.datetime object")
222
329
  datetime_obj = date_obj
223
330
  elif isinstance(date_obj, datetime.date):
224
- # print("temp is a datetime.date object")
225
- # Convert date object to a datetime object at midnight (00:00:00)
226
331
  datetime_obj = datetime.datetime.combine(date_obj, datetime.time.min)
227
332
  elif isinstance(date_obj, np.datetime64):
228
- # Case when the object is a numpy.datetime64, convert it to datetime
229
- datetime_obj = date_obj.astype('datetime64[ms]').astype(datetime.datetime)
333
+ # normalize to datetime (ms precision to avoid timezone pitfalls)
334
+ datetime_obj = date_obj.astype("datetime64[ms]").astype(datetime.datetime)
230
335
  else:
231
- print("temp is neither a datetime.date nor a datetime.datetime object")
232
- print('temp', date_obj)
233
- print('temp type', type(date_obj))
234
- return
336
+ logger.error(
337
+ "Unsupported BUSINESS_DATE type.",
338
+ extra={"value": str(date_obj), "type": str(type(date_obj))},
339
+ )
340
+ raise TypeError(f"Unsupported BUSINESS_DATE type: {type(date_obj)}")
235
341
 
236
- # Convert datetime object to string
237
342
  output_string = datetime_obj.strftime("%Y-%m-%d %H:%M:%S")
343
+ logger.debug("Earliest date computed", extra={"earliest": output_string})
344
+ return output_string
345
+
346
+ def get_current_filterid(self):
347
+ """
348
+ Extract the currently active filter id from the view DDL.
349
+
350
+ Returns:
351
+ int: Filter id parsed from the view's definition.
352
+
353
+ Raises:
354
+ ValueError: If the filter id cannot be parsed from the DDL.
355
+ """
356
+ logger.debug("Reading view DDL to extract current filter id")
357
+ txt = tdfs4ds.utils.lineage.get_ddl(schema_name=self.schema_name, view_name=self.view_name)
358
+ try:
359
+ current = int(txt.split("\n")[-1].split("=")[1])
360
+ logger.info("Current filter id extracted", extra={"filter_id": current})
361
+ return current
362
+ except Exception as exc:
363
+ logger.exception("Failed to parse filter id from view DDL")
364
+ raise ValueError("Unable to parse current filter id from view DDL.") from exc
365
+
366
+ def print_view_ddl(self):
367
+ """
368
+ Log the view definition (DDL) for troubleshooting/traceability.
369
+ """
370
+ ddl = tdfs4ds.utils.lineage.get_ddl(schema_name=self.schema_name, view_name=self.view_name)
371
+ logger.info("View DDL:\n%s", ddl)
372
+
373
+ def prune_filter(self, filter_id=None):
374
+ """
375
+ Remove all filters with ids lower than `filter_id` and renumber remaining ones.
376
+
377
+ If `filter_id` is omitted, the method uses the current filter id from the view.
378
+ After pruning, filter ids are normalized so the smallest remaining id becomes 1,
379
+ and the public view is repointed to filter_id=1.
380
+
381
+ Args:
382
+ filter_id (int, optional): Threshold id; rows with `{filter_id_name} < filter_id` are deleted.
383
+
384
+ Returns:
385
+ FilterManager: Self, to allow method chaining.
386
+ """
387
+ if filter_id is None:
388
+ filter_id = self.get_current_filterid()
389
+
390
+ logger.info("Pruning filters", extra={"threshold_filter_id": filter_id})
391
+
392
+ delete_sql = f"DELETE {self.schema_name}.{self.table_name} WHERE {self.filter_id_name} < {filter_id}"
393
+ update_sql = f"UPDATE {self.schema_name}.{self.table_name} SET {self.filter_id_name} = {self.filter_id_name} - {filter_id} + 1"
394
+
395
+ logger.debug("Executing prune delete", extra={"sql": delete_sql})
396
+ tdml.execute_sql(delete_sql)
397
+
398
+ logger.debug("Executing prune renumber", extra={"sql": update_sql})
399
+ tdml.execute_sql(update_sql)
238
400
 
239
- return output_string
401
+ self.update(1)
402
+ logger.info("Prune complete; active filter set to 1.")
403
+ return self
404
+
405
+ def clone_filter(self, source_filtermanager, filter_id_to_apply=1, take_ownership=False, clone_mode="soft", if_exists="error"):
406
+ """
407
+ Clone filter definitions from another FilterManager.
408
+
409
+ Supports:
410
+ - soft clone (default): just point to source _HIDDEN table
411
+ - hard clone: copy the source _HIDDEN table and own the copy
412
+
413
+ Args:
414
+ source_filtermanager (FilterManager): Source FilterManager to clone.
415
+ filter_id_to_apply (int, optional): Filter ID to activate. Default: 1.
416
+ take_ownership (bool, optional): Whether this manager owns the cloned table (soft mode only).
417
+ clone_mode (str, optional): "soft" or "hard". Default: "soft".
418
+ if_exists (str, optional): Behavior if target hidden table already exists
419
+ - "error" (default): raise an exception
420
+ - "replace": drop and recreate
421
+ - "skip": reuse existing table
422
+
423
+ Returns:
424
+ FilterManager
425
+
426
+ Raises:
427
+ ValueError: On invalid clone_mode or missing source.
428
+ """
429
+ if clone_mode not in ("soft", "hard"):
430
+ raise ValueError("clone_mode must be 'soft' or 'hard'")
431
+ if if_exists not in ("error", "replace", "skip"):
432
+ raise ValueError("if_exists must be 'error', 'replace', or 'skip'")
433
+
434
+ src_schema = source_filtermanager.schema_name
435
+ src_hidden = source_filtermanager.table_name
436
+
437
+ logger.info(
438
+ "Cloning filter",
439
+ extra={
440
+ "mode": clone_mode,
441
+ "source": f"{src_schema}.{src_hidden}",
442
+ "target_view": f"{self.schema_name}.{self.view_name}"
443
+ },
444
+ )
445
+
446
+ # Validate source exists
447
+ existing_src = [t.lower() for t in tdml.db_list_tables(schema_name=src_schema).TableName.values]
448
+ if src_hidden.lower() not in existing_src:
449
+ raise ValueError(f"Source hidden filter table {src_schema}.{src_hidden} does not exist.")
450
+
451
+ if clone_mode == "hard":
452
+ # Hard clone requires a NEW hidden table in this schema
453
+ self.table_name = get_hidden_table_name(self.view_name)
454
+ existing_dest = [t.lower() for t in tdml.db_list_tables(schema_name=self.schema_name).TableName.values]
455
+
456
+ # Handle table existence
457
+ if self.table_name.lower() in existing_dest:
458
+ if if_exists == "error":
459
+ raise RuntimeError(f"Target table {self.schema_name}.{self.table_name} already exists.")
460
+ elif if_exists == "replace":
461
+ logger.warning(f"Replacing existing table {self.schema_name}.{self.table_name}")
462
+ tdml.db_drop_table(schema_name=self.schema_name, table_name=self.table_name)
463
+ elif if_exists == "skip":
464
+ logger.info(f"Skipping clone, using existing {self.schema_name}.{self.table_name}")
465
+ if self.table_name.lower() not in existing_dest or if_exists == "replace":
466
+ # Create cloned table
467
+ logger.info(f"Creating cloned table {self.schema_name}.{self.table_name}")
468
+ create_sql = f"""
469
+ CREATE TABLE {self.schema_name}.{self.table_name} AS
470
+ (SELECT * FROM {src_schema}.{src_hidden})
471
+ WITH DATA
472
+ """
473
+ tdml.execute_sql(create_sql)
474
+
475
+ self._owns_hidden = True # Hard clones always own their copy
476
+ target_schema = self.schema_name
477
+
478
+ else:
479
+ # Soft clone: link to source
480
+ logger.info("Soft clone: linking to source table")
481
+ self.table_name = src_hidden
482
+ self._owns_hidden = bool(take_ownership)
483
+ target_schema = src_schema # view selects from source schema
484
+
485
+ # Load metadata
486
+ df = tdml.DataFrame(tdml.in_schema(target_schema, self.table_name))
487
+ self.filter_id_name = df.columns[0]
488
+ self.time_filtering = "BUSINESS_DATE" in df.columns
489
+ self.col_names = df.columns[2:] if self.time_filtering else df.columns[1:]
490
+ self.nb_filters = df.shape[0]
491
+
492
+ # Rebuild view
493
+ select_cols = ",".join((["BUSINESS_DATE"] if self.time_filtering else []) + list(self.col_names))
494
+ view_sql = f"""
495
+ REPLACE VIEW {self.schema_name}.{self.view_name} AS
496
+ SELECT {select_cols}
497
+ FROM {target_schema}.{self.table_name}
498
+ WHERE {self.filter_id_name} = {int(filter_id_to_apply)}
499
+ """
500
+ tdml.execute_sql(view_sql)
501
+
502
+ logger.info(f"Clone complete → Active filter_id={filter_id_to_apply}")
503
+ return self
504
+
505
+
506
+ def take_ownership(self):
507
+ """
508
+ Take ownership of the currently linked hidden filter table.
509
+
510
+ This enables this FilterManager instance to manage (and potentially drop)
511
+ the hidden table via `_drop()` or future maintenance methods.
512
+
513
+ Returns:
514
+ FilterManager: self (for chaining)
515
+ """
516
+ logger.warning(
517
+ "Ownership taken for hidden table. This manager may now drop or modify it.",
518
+ extra={
519
+ "schema_name": getattr(self, "schema_name_for_table", self.schema_name),
520
+ "table_name": self.table_name
521
+ }
522
+ )
523
+ self._owns_hidden = True
524
+ return self