Ejemplo n.º 1
0
def delete_all_status(event, context):
    """
    deletes all clean or dirty flag for a given target's spectrum
    :param event:
    :param context:
    :return:
    """
    if 'tgt_id' not in event['pathParameters']:
        return invalid_request("Missing path parameters 'tgt_id'")

    tgt_id = event['pathParameters']['tgt_id']
    # splash = urllib.parse.unquote(events['pathParameters']['splash'])
    # method = urllib.parse.unquote(events['pathParameters']['method'])
    # version = urllib.parse.unquote(events['pathParameters']['version'])

    try:
        database.query(
            'DELETE FROM compound_spectrum_quality '
            'WHERE target_id = %(tgt_id)s',
            # 'AND target_splash = %(splash)s '
            # 'AND target_method = %(method)s '
            # 'AND target_version = %(version)s',
            conn,
            {'tgt_id': tgt_id
             })  # , 'splash': splash, 'method': method, 'version': version})

        return no_content()
    except Exception as ex:
        return server_error(ex)
Ejemplo n.º 2
0
def delete_metas(event, context):
    if 'library' not in event['pathParameters']:
        return invalid_request('missing "library" path parameter')
    if 'splash' not in event['pathParameters']:
        return invalid_request('missing "splash" path parameter')

    library = urllib.parse.unquote(event['pathParameters']['library'])
    splash = urllib.parse.unquote(event['pathParameters']['splash'])
    version = urllib.parse.unquote(event['pathParameters'].get(
        'version', 'fixed'))

    result = database.query(
        'SELECT id '
        'FROM compound '
        'WHERE NOT hidden '
        'AND splash=%(splash)s '
        'AND method=%(library)s '
        'AND version=%(version)s ', conn, {
            'splash': splash,
            'library': library,
            'version': version
        })

    if result is not None:
        # compound with metadata exists
        database.query(
            'DELETE FROM compound_meta '
            'WHERE target_id = %(tgt_id)s', conn, {'tgt_id': result[0][0]})

        return no_content()
    else:
        return not_found()
Ejemplo n.º 3
0
def delete_comment(event, context):
    """
    :param event:
    :param context:
    :return:
    """
    # if 'library' not in event['pathParameters']:
    #     return compounds.invalid_request('missing "library" path parameter')
    # if 'splash' not in event['pathParameters']:
    #     return compounds.invalid_request('missing "splash" path parameter')
    if 'identifiedBy' not in event['pathParameters']:
        return compounds.invalid_request('missing "identifiedBy" path parameter')

    # library = urllib.parse.unquote(event['pathParameters']['library'])
    # splash = urllib.parse.unquote(event['pathParameters']['splash'])
    # version = urllib.parse.unquote(event['pathParameters'].get('version', 'fixed'))
    identifiedBy = urllib.parse.unquote(event['pathParameters']['identifiedBy'])
    comment_id = urllib.parse.unquote(event['pathParameters']['comment_id'])

    try:
        database.query(
            "DELETE FROM compound_comment WHERE id = %(comment_id)s AND identified_by = %(identifiedBy)s",
            conn, {'comt_id': comment_id, 'identifiedBy': identifiedBy})
    except Exception as ex:
        return server_error(ex)

    return no_content()
Ejemplo n.º 4
0
def promote_adduct(event, context):
    if 'splash' not in event['pathParameters']:
        return invalid_request('missing "splash" path parameter')
    if 'library' not in event['pathParameters']:
        return invalid_request('missing "library" path parameter')
    if 'name' not in event['pathParameters']:
        return invalid_request('missing "adduct" path parameter')

    library = urllib.parse.unquote(event['pathParameters']['library'])
    splash = urllib.parse.unquote(event['pathParameters']['splash'])
    adduct = urllib.parse.unquote(event['pathParameters']['name'])
    version = urllib.parse.unquote(event['pathParameters'].get(
        'version', 'fixed'))

    result = database.query(
        'SELECT exists (SELECT 1 FROM compound c '
        'WHERE NOT c.hidden '
        'AND c.method = %(library)s '
        'AND c.splash=%(splash)s '
        'AND c.version=%(version)s)', conn, {
            'library': library,
            'splash': splash,
            'version': version
        })

    if result[0][0] == 0:
        return not_found()
    else:
        try:
            response = database.query(
                'UPDATE compound SET adduct = %(adduct)s '
                'WHERE method=%(library)s '
                'AND splash=%(splash)s '
                'AND version=%(version)s', conn, {
                    'adduct': adduct,
                    'library': library,
                    'splash': splash,
                    'version': version
                })

            # create a response
            return {
                'statusCode':
                200,
                'headers':
                headers.__HTTP_HEADERS__,
                'body':
                json.dumps(
                    {
                        'library': library,
                        'splash': splash,
                        'version': version,
                        'adduct': adduct
                    },
                    use_decimal=True)
            }
        except Exception as ex:
            traceback.print_exc()
            return server_error(ex)
Ejemplo n.º 5
0
def promote_name(event, context):
    if 'library' not in event['pathParameters']:
        return invalid_request('missing "library" path parameter')
    if 'splash' not in event['pathParameters']:
        return invalid_request('missing "splash" path parameter')
    if 'name' not in event['pathParameters']:
        return invalid_request('missing "name" path parameter')

    method_name = urllib.parse.unquote(event['pathParameters']['library'])
    splash = urllib.parse.unquote(event['pathParameters']['splash'])
    name = urllib.parse.unquote(event['pathParameters']['name'])
    version = urllib.parse.unquote(event['pathParameters'].get(
        'version', 'fixed'))

    result = database.query(
        'SELECT exists (SELECT 1 FROM compound c '
        'WHERE NOT c.hidden '
        'AND method = %(method)s '
        'AND splash = %(splash)s '
        'AND version = %(version)s)', conn, {
            'method': method_name,
            'splash': splash,
            'version': version
        })

    if result[0][0] == 0:
        return not_found()
    else:
        try:
            database.query(
                'UPDATE compound c SET name = %(name)s '
                'WHERE method = %(method)s '
                'AND splash = %(splash)s '
                'AND version = %(version)s', conn, {
                    'name': name,
                    'method': method_name,
                    'splash': splash,
                    'version': version
                })

            # create a response
            return {
                'statusCode':
                200,
                'headers':
                headers.__HTTP_HEADERS__,
                'body':
                json.dumps(
                    {
                        'library': method_name,
                        'splash': splash,
                        'version': version,
                        'name': name
                    },
                    use_decimal=True)
            }
        except Exception as ex:
            return server_error(ex)
Ejemplo n.º 6
0
def delete_adduct(event, context):
    """
    :param event:
    :param context:
    :return:
    """
    if 'splash' not in event['pathParameters']:
        return invalid_request('missing "splash" path parameter')
    if 'library' not in event['pathParameters']:
        return invalid_request('missing "library" path parameter')
    if 'name' not in event['pathParameters']:
        return invalid_request('missing "name" path parameter')
    if 'identifiedBy' not in event['pathParameters']:
        return invalid_request('missing "identifiedBy" path parameter')

    splash = urllib.parse.unquote(event['pathParameters']['splash'])
    library = urllib.parse.unquote(event['pathParameters']['library'])
    identified_by = urllib.parse.unquote(
        event['pathParameters']['identifiedBy'])
    name = urllib.parse.unquote(event['pathParameters']['name'])
    version = urllib.parse.unquote(event['pathParameters'].get(
        'version', 'fixed'))

    result = database.query(
        'SELECT DISTINCT ca.id, c.id, c.name '
        'FROM compound c, compound_adduct ca '
        'WHERE NOT c.hidden '
        'AND c.id = ca.target_id '
        'AND splash = %(splash)s '
        'AND method = %(method)s '
        'AND version = %(version)s '
        'AND ca.name = %(name)s '
        'AND identified_by = %(identified_by)s', conn, {
            'splash': splash,
            'method': library,
            'name': name,
            'identified_by': identified_by,
            'version': version
        })

    if result is not None:
        adduct_id = result[0][0]
        target_id = result[0][1]
        target_name = result[0][2]

        if name == target_name:
            database.query(
                "UPDATE compound SET adduct = NULL WHERE id = %(target_id)s",
                conn, {'target_id': target_id})

        database.query("DELETE FROM compound_adduct WHERE id = %(adduct_id)s",
                       conn, {'adduct_id': adduct_id})

        return no_content()

    else:
        return not_found()
Ejemplo n.º 7
0
def delete_meta(event, context):
    '''
    deletes a single metadata item from a specific compound, matched by name and value.
    :param event:
    :param context:
    :return:
    '''
    if 'library' not in event['pathParameters']:
        return compounds.invalid_request('missing "library" path parameter')
    if 'splash' not in event['pathParameters']:
        return compounds.invalid_request('missing "splash" path parameter')
    if 'name' not in event['pathParameters']:
        return compounds.invalid_request('missing "name" path parameter')
    if 'value' not in event['pathParameters']:
        return compounds.invalid_request('missing "value" path parameter')
    if 'identifiedBy' not in event['pathParameters']:
        return compounds.invalid_request(
            'missing "identifiedBy" path parameter')

    library = urllib.parse.unquote(event['pathParameters']['library'])
    splash = urllib.parse.unquote(event['pathParameters']['splash'])
    version = urllib.parse.unquote(event['pathParameters'].get(
        'version', 'fixed'))
    name = urllib.parse.unquote(event['pathParameters']['name'])
    value = urllib.parse.unquote(event['pathParameters']['value'])
    identifiedBy = urllib.parse.unquote(
        event['pathParameters']['identifiedBy'])

    result = database.query(
        f'SELECT id, splash, method, version '
        f'FROM compound '
        f'WHERE NOT hidden '
        f'AND method = %(method)s '
        f'AND splash = %(splash)s '
        f'AND version = %(version)s', conn, {
            'splash': splash,
            'method': library,
            'version': version
        })

    if result is not None:
        try:
            database.query(
                'DELETE FROM compound_meta '
                'WHERE target_id = %(tgt_id)s '
                'AND name = %(name)s '
                'AND value = %(value)s '
                'AND identified_by = %(identifiedBy)s ', conn, {
                    'tgt_id': result[0][0],
                    'name': name,
                    'value': value,
                    'identifiedBy': identifiedBy
                })
        except Exception as ex:
            return server_error(ex)

    return no_content()
Ejemplo n.º 8
0
def reject_name(event, context):
    if 'name_id' not in event['pathParameters']:
        return invalid_request('Missing id of the name to reject')
    if 'compound_id' not in event['pathParameters']:
        return invalid_request('missing id of the compound to modify')
    if 'rejected' not in event['pathParameters'] or \
            event['pathParameters']['rejected'].lower() not in ['true', 'false']:
        return invalid_request(
            'Invalid rejection value. Please use true or false')

    try:
        name_id = urllib.parse.unquote(
            str(event['pathParameters'].get('name_id', '')))
        compound_id = urllib.parse.unquote(
            str(event['pathParameters'].get('compound_id', '')))
        rejected = urllib.parse.unquote(
            str(event['pathParameters'].get('rejected', 'false')))
    except Exception as ex:
        logger.error(ex.args)
        return server_error(ex)

    result = database.query(
        'SELECT c.id, pre_cursors_mass, retention_index, cn.id, c.name, cn.name, c.name = cn.name as promoted '
        'FROM compound c LEFT JOIN compound_name cn on c.id=cn.target_id '
        'WHERE cn.id = %(name_id)s', conn, {'name_id': name_id})

    if result is not None:
        promoted = result[0][6]
        target_mz = result[0][1]
        target_ri = result[0][2]
        unk_name = f'unknown_{target_mz:.4f}_{target_ri:.4f}'

        # compound with name exists
        database.html_response_query(
            'UPDATE compound_name '
            'SET rejected = %(rejected)s '
            'WHERE id = %(name_id)s', conn, {
                'rejected': rejected,
                'name_id': name_id,
                'compound_id': compound_id
            })

        if promoted and rejected:
            database.query(
                'UPDATE compound '
                'SET name = %(unk_name)s '
                'WHERE id = %(tgt_id)s', conn, {
                    'unk_name': unk_name,
                    'tgt_id': compound_id
                })

        return no_content()
    else:
        return not_found()
Ejemplo n.º 9
0
def delete(event, context):
    """ hide istd """
    if 'id' not in event['pathParameters']:
        return compounds.invalid_request('Missing "id" pathParameter')
    istd_id = int(urllib.parse.unquote(event['pathParameters'].get('id', '0')))

    try:
        database.query('UPDATE compound SET hidden = true WHERE id = %(id)s',
                       conn, {'id': istd_id})
        return {
            'statusCode': http.HTTPStatus.NO_CONTENT,
            'headers': headers.__HTTP_HEADERS__
        }
    except Exception as ex:
        return compounds.server_error(ex)
Ejemplo n.º 10
0
def compound_without_associated_comments(request, conn):
    result = request.config.cache.get('cis/compound_without_comment', None)

    compound = result
    if result is None:
        result = database.query(
            'SELECT c.id, method, splash, sample, version, pre_cursors_mass, retention_index '
            'FROM compound_consensus c LEFT JOIN compound_comment cc ON c.id = cc.target_id '
            "WHERE cc.comment='' OR cc.comment IS NULL "
            'LIMIT 1', conn)

        if result is None:
            pytest.fail("Can't find compounds in database")

        transform = lambda x: {
            'id': x[0],
            'method': x[1],
            'splash': x[2],
            'sample': x[3],
            'version': x[4],
            'mass': x[5],
            'ri': x[6]
        }

        compound = list(map(transform, result))[0]

        request.config.cache.set('cis/compound_without_comment', compound)
    else:
        print('using cached data')
        compound = result

    return compound
Ejemplo n.º 11
0
def delete_status(event, context):
    """
    deletes a clean or dirty flag for a given target's spectrum
    :param event:
    :param context:
    :return:
    """
    if 'tgt_id' not in event['pathParameters']:
        return invalid_request("Missing path parameters 'tgt_id'")

    tgt_id = urllib.parse.unquote(event['pathParameters']['tgt_id'])

    if 'queryStringParameters' not in event or 'identifiedBy' not in event[
            'queryStringParameters']:
        return invalid_request("Missing query string parameter 'identifiedBy'")

    identified_by = event['queryStringParameters']['identifiedBy']

    try:
        result = database.query(
            'DELETE FROM compound_spectrum_quality '
            'WHERE target_id = %s AND identified_by = %s', conn,
            [tgt_id, identified_by])

        response = {"statusCode": 204, "headers": headers.__HTTP_HEADERS__}
    except Exception as ex:
        logger.error(str(ex))
        response = {
            "statusCode": 500,
            "headers": headers.__HTTP_HEADERS__,
            "body": json.dumps({"error": str(ex)}, use_decimal=True)
        }

    return response
Ejemplo n.º 12
0
def counts(events, context):
    try:
        result = database.query(
            'SELECT DISTINCT method, target_type, count(*) '
            'FROM compound '
            'WHERE NOT hidden '
            'GROUP BY method, target_type', conn)
        data = list(
            map(lambda x: {
                'method': x[0],
                'target_type': x[1],
                'count': x[2]
            }, result))

        # create a response
        return {
            'statusCode': 200,
            'headers': headers.__HTTP_HEADERS__,
            'body': json.dumps(data, use_decimal=True)
        }
    except Exception as e:
        traceback.print_exc()
        return {
            "statusCode": 500,
            "headers": headers.__HTTP_HEADERS__,
            "body": json.dumps({"error": e.args}, use_decimal=True)
        }
Ejemplo n.º 13
0
def compound_list_with_dupes(request, conn):
    result = request.config.cache.get('cis/comps_with_dupes', None)

    if result is not None:
        print(f"using cached object: {result}")
    else:
        print("loading all, takes forever and should be cached instead...")
        libs = database.query(
            'SELECT id, method, splash, version FROM compound_consensus '
            'WHERE id IN ('
            'SELECT duplicate_of FROM compound_consensus WHERE duplicate_of IS NOT NULL)',
            conn)

        if len(libs) == 0:
            pytest.fail('No compounds with duplicates in db')

        result = [{
            'id': l[0],
            'library': l[1],
            'splash': l[2],
            'version': l[3]
        } for l in libs]
        request.config.cache.set('cis/comps_with_dupes', result)

    return result
Ejemplo n.º 14
0
def comps_with_adducts(request, conn):
    result = request.config.cache.get('cis/comp_with_adducts', None)

    if result is not None:
        print(f"using cached object: {result}")
    else:
        print("loading all, takes forever and should be cached instead...")
        libs = database.query(
            'SELECT c.id, method, splash, sample, version, '
            'pre_cursors_mass, retention_index, target_type, c.name, ca.name as adduct '
            'FROM compound_consensus c LEFT JOIN compound_adduct ca on c.id = ca.target_id '
            'WHERE ca.name IS NOT NULL LIMIT 100', conn)
        result = list(
            map(
                lambda x: {
                    'id': x[0],
                    'method': x[1],
                    'splash': x[2],
                    'sample': x[3],
                    'version': x[4],
                    'mass': x[5],
                    'ri': x[6],
                    'target_type': x[7],
                    'name': x[8],
                    'adduct': x[9]
                }, libs))
        request.config.cache.set('cis/comp_with_adducts', result)

    return result
Ejemplo n.º 15
0
def reject_adduct(event, context):
    if 'adduct_id' not in event['pathParameters']:
        return invalid_request('Missing id of the adduct to reject')
    if 'compound_id' not in event['pathParameters']:
        return invalid_request('Missing id of compound to modify')
    if 'rejected' not in event['pathParameters'] or \
            event['pathParameters']['rejected'].lower() not in ['true', 'false']:
        return invalid_request(
            'Invalid rejection value. Please use true or false')

    adduct_id = urllib.parse.unquote(event['pathParameters']['adduct_id'])
    compound_id = urllib.parse.unquote(event['pathParameters']['compound_id'])
    rejected = urllib.parse.unquote(event['pathParameters']['rejected'])

    result = database.query(
        'SELECT c.id, ca.id, c.adduct, ca.name, c.adduct = ca.name as promoted '
        'FROM compound c LEFT JOIN compound_adduct ca on c.id=ca.target_id '
        'WHERE ca.id = %(adduct_id)s', conn, {'adduct_id': adduct_id})

    if result is not None:
        promoted = result[0][4]

        try:
            # compound with existing adduct
            database.html_response_query(
                'UPDATE compound_adduct '
                'SET rejected = %(rejected)s '
                'WHERE id = %(adduct_id)s '
                'AND target_id = %(compound_id)s', conn, {
                    'rejected': rejected,
                    'adduct_id': adduct_id,
                    'compound_id': compound_id
                })

            if promoted:
                database.query(
                    'UPDATE compound '
                    'SET adduct = null '
                    'WHERE id = %(tgt_id)s', conn, {'tgt_id': compound_id})
        except Exception as ex:
            return server_error(ex)

        return no_content()
    else:
        return no_content()
Ejemplo n.º 16
0
def delete_names(event, context):
    if 'splash' not in event['pathParameters']:
        return invalid_request('missing "splash" path parameter')
    if 'library' not in event['pathParameters']:
        return invalid_request('missing "library" path parameter')

    splash = urllib.parse.unquote(event['pathParameters']['splash'])
    library = urllib.parse.unquote(event['pathParameters']['library'])
    version = urllib.parse.unquote(event['pathParameters'].get(
        'version', 'fixed'))

    result = database.query(
        'SELECT id, pre_cursors_mass, retention_index '
        'FROM compound '
        'WHERE NOT hidden '
        'AND splash = %(splash)s '
        'AND method = %(method)s '
        'AND version = %(version)s', conn, {
            'splash': splash,
            'method': library,
            'version': version
        })

    if result is not None:
        target_id = result[0][0]
        target_mz = result[0][1]
        target_ri = result[0][2]
        unk_name = f'unknown_{target_mz:.4f}_{target_ri:.4f}'

        # compound with adducts exists
        database.query(
            'DELETE FROM compound_name WHERE target_id = %(tgt_id)s', conn,
            {'tgt_id': target_id})

        database.query(
            'UPDATE compound SET name = %(unk_name)s WHERE id = %(tgt_id)s',
            conn, {
                'unk_name': unk_name,
                'tgt_id': target_id
            })

        return no_content()
    else:
        return not_found()
Ejemplo n.º 17
0
def save(event, context):
    """create / update"""

    obj = json.loads(event['body'])
    obj['created'] = event['requestContext']['requestTime']
    try:
        if event['httpMethod'] == 'POST':
            # create / post
            new_data = database.query(
                "INSERT INTO compound (id, method, splash, version, accurate_mass, adduct, hidden, inchi_key, "
                "ion_mode, msms, name, pre_cursors_mass, retention_index, sample, target_type, created, updated) "
                "VALUES (nextval('compound_id'), %(method)s, %(splash)s, %(version)s, %(accurate_mass)s, %(adduct)s, "
                "%(hidden)s, %(inchi_key)s, %(ion_mode)s, %(msms)s, %(name)s, %(pre_cursors_mass)s, "
                "%(retention_index)s, %(sample)s, 'ISTD', %(created)s, %(created)s) "
                'RETURNING id, method, splash, version, accurate_mass, name, adduct, hidden, inchi_key, ion_mode, '
                'msms, pre_cursors_mass, retention_index, target_type, sample',
                conn, obj)
            new_istd = list(map(istd_transform, new_data))[0]

            return {
                'statusCode': http.HTTPStatus.CREATED,
                'headers': headers.__HTTP_HEADERS__,
                'body': json.dumps(new_istd, use_decimal=True)
            }
        elif event['httpMethod'] == 'PUT':
            # update / put
            database.query(
                'UPDATE compound SET method = %(method)s, splash = %(splash)s, version = %(version)s, '
                'accurate_mass = %(accurate_mass)s, adduct = %(adduct)s, hidden = %(hidden)s, '
                'inchi_key = %(inchi_key)s, ion_mode = %(ion_mode)s, msms = %(msms)s, name = %(name)s, '
                'pre_cursors_mass = %(pre_cursors_mass)s, retention_index = %(retention_index)s '
                'WHERE id = %(id)s', conn, obj)

            return {
                'statusCode': http.HTTPStatus.OK,
                'headers': headers.__HTTP_HEADERS__,
                'body': json.dumps(obj, use_decimal=True)
            }
        else:
            return compounds.invalid_request('Invalid request method')
    except Exception as ex:
        print(str(ex))
        return compounds.server_error(ex)
Ejemplo n.º 18
0
def process_event(events, query_str):
    if 'method' not in events['pathParameters']:
        return invalid_request('missing or invalid method path parameter')

    method = urllib.parse.unquote(events['pathParameters']['method'])
    version = urllib.parse.unquote(events['pathParameters'].get('version'))

    # check if they request a compound or a sample
    if 'object_type' not in events['pathParameters'] or \
            events['pathParameters']['object_type'] not in ['target', 'sample']:
        return invalid_request(
            'missing or invalid object type, it should be <target|sample>')
    else:
        object_type = urllib.parse.unquote(
            events['pathParameters']['object_type'])

    # get the splash or sample name for query depending on 'object_type'
    if 'value' not in events['pathParameters']:
        if object_type == 'target':
            return invalid_request('missing splash as value path parameter')
        else:
            return invalid_request(
                'missing sample name as value path parameter')
    else:
        value = urllib.parse.unquote(events['pathParameters']['value'])

    filters = {'value': value, 'version': version, 'method': method}

    if object_type == 'target':
        query = query_str.replace('@column_name@', 'splash')
    else:
        query = query_str.replace('@column_name@', 'sample')

    try:
        caller = inspect.stack()[1][3]
        result = database.query(query, conn, filters)
        code = http.HTTPStatus.NOT_FOUND if result is None else http.HTTPStatus.OK

        # create a response
        return {
            'statusCode':
            code,
            'headers':
            headers.__HTTP_HEADERS__,
            'body':
            json.dumps(
                {
                    caller: result,
                    'object_type': object_type,
                    'filters': filters
                },
                use_decimal=True)
        }
    except Exception as ex:
        return server_error(ex)
Ejemplo n.º 19
0
def delete_comments(event, context):
    if 'library' not in event['pathParameters']:
        return invalid_request('missing "library" path parameter')
    if 'splash' not in event['pathParameters']:
        return invalid_request('missing "splash" path parameter')

    library = urllib.parse.unquote(event['pathParameters']['library'])
    splash = urllib.parse.unquote(event['pathParameters']['splash'])
    version = urllib.parse.unquote(event['pathParameters'].get('version', 'fixed'))

    try:
        database.query(
            'DELETE FROM compound_comment '
            'WHERE target_splash = %(splash)s '
            'AND target_method = %(method)s '
            'AND target_version = %(version)s',
            conn, {'splash': splash, 'method': library, 'version': version})
    except Exception as ex:
        return server_error(ex)

    return no_content()
Ejemplo n.º 20
0
def libraries_list(request, conn) -> list:
    libs = request.config.cache.get('cis/libraries', None)

    if libs is None:
        libs = database.query('SELECT DISTINCT method FROM compound', conn)

        if libs is not None:
            libs = [l[0] for l in libs]
            request.config.cache.set('cis/libraries', libs)
        else:
            pytest.fail("Didn't find libraries in the database.")

    return libs
Ejemplo n.º 21
0
 def get_duplicates_list(tgt_id):
     dupes = database.query(
         'SELECT id, method, splash, version FROM compound WHERE duplicate_of = %(tgt_id)s',
         conn,
         params={'tgt_id': tgt_id})
     if dupes is None:
         return []
     else:
         return [{
             'id': y[0],
             'method': y[1],
             'splash': y[2],
             'version': y[3]
         } for y in dupes]
Ejemplo n.º 22
0
def delete(event, context):
    if 'pathParameters' in event:
        if 'library' in event['pathParameters']:
            method_name = urllib.parse.unquote(
                event['pathParameters']['library'])

            result = database.query('DELETE FROM compound WHERE "method" = %s',
                                    conn, [method_name])

            try:
                # create a response
                return {
                    "statusCode": 200,
                    "headers": headers.__HTTP_HEADERS__,
                    "body": json.dumps({"library": method_name},
                                       use_decimal=True)
                }
            except Exception as e:
                traceback.print_exc()
                return {
                    "statusCode":
                    500,
                    "headers":
                    headers.__HTTP_HEADERS__,
                    "body":
                    json.dumps({
                        "error": str(e),
                        "library": method_name
                    },
                               use_decimal=True)
                }
        else:
            return {
                "statusCode":
                500,
                "headers":
                headers.__HTTP_HEADERS__,
                "body":
                json.dumps({"error": "you need to provide a 'method' name"},
                           use_decimal=True)
            }
    else:
        return {
            "statusCode":
            500,
            "headers":
            headers.__HTTP_HEADERS__,
            "body":
            json.dumps({"error": "missing path parameters"}, use_decimal=True)
        }
Ejemplo n.º 23
0
def size(events, context):
    if 'library' in events['pathParameters']:

        method_name = urllib.parse.unquote(events['pathParameters']['library'])

        try:
            result = database.query(
                'SELECT count(*), target_type '
                'FROM compound '
                'WHERE NOT hidden '
                'AND method = %(method)s '
                'GROUP BY target_type', conn, {'method': method_name})

            data = list(
                map(lambda x: {
                    'target_type': x[1],
                    'count': x[0]
                }, result))

            # create a response
            return {
                'statusCode': 200,
                'headers': headers.__HTTP_HEADERS__,
                'body': json.dumps(data, use_decimal=True)
            }
        except Exception as e:
            traceback.print_exc()
            return {
                "statusCode":
                500,
                "headers":
                headers.__HTTP_HEADERS__,
                "body":
                json.dumps({
                    "error": str(e),
                    "library": method_name
                },
                           use_decimal=True)
            }
    else:
        return {
            "statusCode":
            500,
            "headers":
            headers.__HTTP_HEADERS__,
            "body":
            json.dumps({"error": "you need to provide a 'method' name"},
                       use_decimal=True)
        }
Ejemplo n.º 24
0
 def generate_status_list(tgt_id):
     stats = database.query(
         'SELECT id, clean, target_id, identified_by FROM compound_spectrum_quality '
         'WHERE target_id = %(tgt_id)s '
         'LIMIT 10 OFFSET 0',
         conn,
         params={'tgt_id': tgt_id})
     if stats is None:
         return []
     else:
         return [{
             'status_id': y[0],
             'clean': y[1],
             'target_id': y[2],
             'identifiedBy': y[3]
         } for y in stats]
Ejemplo n.º 25
0
def duplicates_of_compound(event, context):
    """
    Lists all duplicate splashes for a given compound
    :param event:
    :param context:
    :return:
    """
    if 'library' not in event['pathParameters']:
        return invalid_request('Missing library path parameter')
    if 'splash' not in event['pathParameters']:
        return invalid_request('Missing splash path parameter')

    library = urllib.parse.unquote(event['pathParameters'].get('library', ''))
    splash = urllib.parse.unquote(event['pathParameters'].get('splash', ''))
    version = urllib.parse.unquote(event['pathParameters'].get(
        'version', 'fixed'))

    result = database.query(
        'SELECT id, method, splash, version FROM compound '
        'WHERE duplicate_of = ('
        '   SELECT id FROM compound '
        '   WHERE method = %(library)s '
        '   AND splash = %(splash)s '
        '   AND version = %(version)s '
        ')',
        conn,
        params={
            'library': library,
            'splash': splash,
            'version': version
        })

    if result is None:
        return not_found()

    result = [{
        'id': x[0],
        'library': x[1],
        'splash': x[2],
        'version': x[3]
    } for x in result]

    return {
        'statusCode': http.HTTPStatus.OK,
        'headers': headers.__HTTP_HEADERS__,
        'body': json.dumps(result)
    }
Ejemplo n.º 26
0
def exists(events, context):
    if 'library' in events['pathParameters']:

        method_name = urllib.parse.unquote(events['pathParameters']['library'])

        result = database.query(
            'SELECT exists (SELECT 1 FROM compound WHERE method = %(method)s)',
            conn, {'method': method_name})

        try:
            # create a response
            return {
                "statusCode":
                200 if result[0][0] is True else 404,
                "headers":
                headers.__HTTP_HEADERS__,
                "body":
                json.dumps({
                    "exists": result[0][0],
                    "library": method_name
                },
                           use_decimal=True)
            }
        except Exception as e:
            traceback.print_exc()
            return {
                "statusCode":
                500,
                "headers":
                headers.__HTTP_HEADERS__,
                "body":
                json.dumps({
                    "error": str(e),
                    "library": method_name
                },
                           use_decimal=True)
            }
    else:
        return {
            "statusCode":
            400,
            "headers":
            headers.__HTTP_HEADERS__,
            "body":
            json.dumps({"error": "you need to provide a 'method' name"},
                       use_decimal=True)
        }
Ejemplo n.º 27
0
def libraries_with_unconfirmed(request, conn) -> list:
    libs = request.config.cache.get('cis/libraries_unconfirmed', None)

    if libs is None:
        libs = database.query(
            'SELECT DISTINCT method, splash '
            'FROM compound_consensus '
            "WHERE lower(target_type) = 'unconfirmed'"
            'ORDER BY splash', conn)

        if libs is not None:
            libs = [{'library': l[0], 'splash': l[1]} for l in libs]
            request.config.cache.set('cis/libraries_unconfirmed', libs)
        else:
            pytest.fail("Didn't find libraries in the database.")

    return libs
Ejemplo n.º 28
0
    def generate_comments_list(tgt_id):
        comments = database.query(
            'SELECT id, comment, identified_by, rejected '
            'FROM compound_comment '
            'WHERE target_id = %(tgt_id)s', conn, {'tgt_id': tgt_id})

        logger.info(f'received comments: {comments}')
        if comments is None:
            return []
        else:
            return list(
                map(
                    lambda y: {
                        'id': y[0],
                        'identifiedBy': y[2],
                        'comment': y[1],
                        'rejected': y[3]
                    }, comments))
Ejemplo n.º 29
0
def libs_with_hidden_comps(request, conn):
    result = request.config.cache.get('cis/libs_with_hidden_comps', None)

    if result is not None:
        print(f"using cached object: {result}")
    else:
        print("loading all, takes forever and should be cached instead...")
        libs = database.query(
            'SELECT distinct method FROM compound_consensus WHERE hidden',
            conn)

        if len(libs) == 0:
            pytest.fail('No libraries with hidden compounds in db')

        result = [x[0] for x in libs]
        request.config.cache.set('cis/libs_with_hidden_comps', result)

    return result
Ejemplo n.º 30
0
    def generate_name_list(tgt_id):
        names = database.query(
            'SELECT id, name, identified_by, comment, rejected '
            'FROM compound_name '
            'WHERE target_id = %(tgt_id)s', conn, {'tgt_id': tgt_id})

        logger.info(f'received names: {names}')
        if names is None:
            return []
        else:
            return list(
                map(
                    lambda y: {
                        'id': y[0],
                        'name': y[1],
                        'identifiedBy': y[2],
                        'comment': y[3],
                        'rejected': y[4]
                    }, names))