Skip to content

Commit 929730b

Browse files
committed
API: passing Artifact.unique_ids
1 parent c16ef72 commit 929730b

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

qiita_db/artifact.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1758,3 +1758,51 @@ def human_reads_filter_method(self, value):
17581758
SET human_reads_filter_method_id = %s
17591759
WHERE artifact_id = %s"""
17601760
qdb.sql_connection.TRN.add(sql, [idx[0], self.id])
1761+
1762+
def unique_ids(self):
1763+
r"""Return a stable mapping of sample_name to integers
1764+
1765+
Obtain a map from a sample_name to an integer. The association is
1766+
unique Qiita-wide and 1-1.
1767+
1768+
This method is idempotent.
1769+
1770+
Returns
1771+
------
1772+
dict
1773+
{sample_name: integer_index}
1774+
"""
1775+
if len(self.prep_templates) == 0:
1776+
raise ValueError("No associated prep template")
1777+
1778+
if len(self.prep_templates) > 1:
1779+
raise ValueError("Cannot assign against multiple prep templates")
1780+
1781+
paired = [[self._id, ps_idx] for ps_idx in sorted(self.prep_templates[0].unique_ids().values())]
1782+
1783+
with qdb.sql_connection.TRN:
1784+
# insert any IDs not present
1785+
sql = """INSERT INTO map_artifact_sample_idx (artifact_idx, prep_sample_idx)
1786+
VALUES (%s, %s)
1787+
ON CONFLICT (artifact_idx, prep_sample_idx)
1788+
DO NOTHING"""
1789+
qdb.sql_connection.TRN.add(sql, paired, many=True)
1790+
1791+
# obtain the association
1792+
sql = """SELECT
1793+
sample_name,
1794+
artifact_sample_idx
1795+
FROM map_artifact_sample_idx
1796+
JOIN map_prep_sample_idx USING (prep_sample_idx)
1797+
JOIN map_sample_idx USING (sample_idx)
1798+
WHERE artifact_idx=%s
1799+
"""
1800+
qdb.sql_connection.TRN.add(sql, [self._id, ])
1801+
1802+
# form into a dict
1803+
mapping = {r[0]: r[1] for r in qdb.sql_connection.TRN.execute_fetchindex()}
1804+
1805+
# commit in the event changes were made
1806+
qdb.sql_connection.TRN.commit()
1807+
1808+
return mapping

qiita_db/test/test_artifact.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1236,7 +1236,7 @@ def test_delete_as_output_job(self):
12361236
def test_unique_ids(self):
12371237
art = qdb.artifact.Artifact(1)
12381238
obs = art.unique_ids()
1239-
exp = {name: idx for idx, name in enumerate(sorted(art.prep_templates[0].keys()))}
1239+
exp = {name: idx for idx, name in enumerate(sorted(art.prep_templates[0].keys()), 1)}
12401240
self.assertEqual(obs, exp)
12411241

12421242
# verify repeat calls are unchanged

0 commit comments

Comments
 (0)