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