"""Connection to Neo4J.""" import time from neo4j import GraphDatabase class DBConnection: """Neo4J related functions.""" def __init__(self, uri, user, password): """Initialize driver.""" self.driver = None self.uri = uri self.user = user self.password = password self.open_connection() def open_connection(self): """Open connection to database.""" self.driver = GraphDatabase.driver(self.uri, auth=(self.user, self.password)) def close(self): """Close driver.""" self.driver.close() def _check_label_participant(self, spotify_id): cypher_query = f'match (n:LabelParticipant' \ f'{{spotifyId:\"{spotify_id}\"}}) return n;' with self.driver.session() as session: result = session.run(cypher_query) fields = [record['n'] for record in result] if len(fields) == 0: return False return True def remove_existing_label_participant(self, spotify_id): """Remove label participant if present.""" data_present = self._check_label_participant(spotify_id) if not data_present: print('nothing to delete') return delete_query = f'match (n:LabelParticipant' \ f'{{spotifyId:\"{spotify_id}\"}}) DETACH DELETE n;' with self.driver.session() as session: session.run(delete_query) def wait_for_label_participant(self, spotify_id, tries): """Wait until label participant node exists.""" data_present = False for i in range(0, tries): data_present = self._check_label_participant(spotify_id) if data_present: break time.sleep(2) return data_present def get_identity_profiles(self, email, tries=10): """Get identity and profile nodes.""" cypher_query = f'match (i:Identity{{email:\"{email}\"}})' \ f'--(p:Profile) return i.email, p.brand;' with self.driver.session() as session: for i in range(0, tries): results = session.run(cypher_query) data = results.data() if data or i == (tries - 1): break print(f'No profiles found. Retying {i+1}/{tries-1}') time.sleep(5) return data