@@ -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
0 commit comments