Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add data parameter to _detect_relationships method #2190

Merged
merged 5 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions sdv/metadata/multi_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,8 +497,14 @@ def _validate_all_tables_connected(self, parent_map, child_map):
f'The relationships in the dataset are disjointed. {table_msg}'
)

def _detect_relationships(self):
"""Automatically detect relationships between tables."""
def _detect_relationships(self, data=None):
"""Automatically detect relationships between tables.

Args:
data (dict):
Dictionary of table names to dataframes.
NOTE: this is only used in SDV-Enterprise.
"""
for parent_candidate in self.tables.keys():
primary_key = self.tables[parent_candidate].primary_key
for child_candidate in self.tables.keys() - {parent_candidate}:
Expand Down Expand Up @@ -552,7 +558,7 @@ def detect_from_dataframes(self, data):
for table_name, dataframe in data.items():
self.detect_table_from_dataframe(table_name, dataframe)

self._detect_relationships()
self._detect_relationships(data)

def detect_table_from_csv(self, table_name, filepath, read_csv_parameters=None):
"""Detect the metadata for a table from a csv file.
Expand All @@ -579,7 +585,9 @@ def detect_from_csvs(self, folder_name, read_csv_parameters=None):
Args:
folder_name (str):
Name of the folder to detect the metadata from.

read_csv_parameters (dict):
A python dictionary of with string and value accepted by ``pandas.read_csv``
function. Defaults to ``None``.
"""
folder_path = Path(folder_name)

Expand All @@ -595,7 +603,12 @@ def detect_from_csvs(self, folder_name, read_csv_parameters=None):
table_name = csv_file.stem
self.detect_table_from_csv(table_name, str(csv_file), read_csv_parameters)

self._detect_relationships()
read_csv_parameters = read_csv_parameters or {}
data = {
csv_file.stem: pd.read_csv(str(csv_file), **read_csv_parameters)
for csv_file in csv_files
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we just add the data to the dict in the for loop above?

self._detect_relationships(data)

def set_primary_key(self, table_name, column_name):
"""Set the primary key of a table.
Expand Down
15 changes: 9 additions & 6 deletions tests/unit/metadata/test_multi_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -2415,6 +2415,10 @@ def test_detect_from_csvs(self, tmp_path):
assert instance.detect_table_from_csv.call_count == 2

instance._detect_relationships.assert_called_once()
table1 = instance._detect_relationships.call_args[0][0]['table1']
table2 = instance._detect_relationships.call_args[0][0]['table2']
pd.testing.assert_frame_equal(table1, data1)
pd.testing.assert_frame_equal(table2, data2)

def test_detect_from_csvs_no_csv(self, tmp_path):
"""Test the ``detect_from_csvs`` method with no csv file in the folder."""
Expand All @@ -2426,13 +2430,11 @@ def test_detect_from_csvs_no_csv(self, tmp_path):
json_file.write('{"key": "value"}')

# Run and Assert
expected_message = re.escape("No CSV files detected in the folder '{}'.".format(tmp_path))
expected_message = re.escape(f"No CSV files detected in the folder '{tmp_path}'.")
with pytest.raises(ValueError, match=expected_message):
instance.detect_from_csvs(tmp_path)

expected_message_folder = re.escape(
"The folder '{}' does not exist.".format('not_a_folder')
)
expected_message_folder = re.escape(f"The folder '{'not_a_folder'}' does not exist.")
with pytest.raises(ValueError, match=expected_message_folder):
instance.detect_from_csvs('not_a_folder')

Expand Down Expand Up @@ -2516,14 +2518,15 @@ def test_detect_from_dataframes(self):

guests_table = pd.DataFrame()
hotels_table = pd.DataFrame()
data = {'guests': guests_table, 'hotels': hotels_table}

# Run
metadata.detect_from_dataframes(data={'guests': guests_table, 'hotels': hotels_table})
metadata.detect_from_dataframes(data)

# Assert
metadata.detect_table_from_dataframe.assert_any_call('guests', guests_table)
metadata.detect_table_from_dataframe.assert_any_call('hotels', hotels_table)
metadata._detect_relationships.assert_called_once()
metadata._detect_relationships.assert_called_once_with(data)

def test_detect_from_dataframes_no_dataframes(self):
"""Test ``detect_from_dataframes`` with no dataframes in the input.
Expand Down
Loading