def add_donation(name): """ add a donation for a new or existing donor """ driver = login_database.login_neo4j_cloud() with driver.session() as session: if name not in get_donor_list(): addname = input("The name you selected is not in the list," " would you like to add it(y/n)? ") if addname[0].lower() == 'y': amount = get_amount() session.run( "create (n:Person {full_name: '%s', donation: [%02.2f]})" % (name, amount)) elif addname.lower() == 'exit': return else: print("\nName was not added, try again\n") return else: log.info(f'Donor {name} found in database') amount = get_amount() donor_names = session.run( "MATCH (n:Person) return n.full_name, n.donation") for d in donor_names: if name == d[0]: d[1].append(amount) session.run( "MATCH (n:Person { full_name: '%s' }) SET n.donation = %a" % (name, d[1]))
def delete_donor(name): """ Delete donor """ log.info('Working with Neo4j delete_donor function') log.info('Updating Donor record...') try: driver = login_database.login_neo4j_cloud() with driver.session() as session: donor_id = name.replace(' ', '_').lower() cyph = """MATCH (p:Donor { id: '%s' }) DETACH DELETE p """ % (donor_id) session.run(cyph) cyph = """MATCH (d:Donation { donor_id: '%s' }) DELETE d """ % (donor_id) session.run(cyph) log.info('Donor {} deleted.'.format(name)) except Exception as e: log.info(e) finally: log.info('Neo4j delete_donor complete')
def add_donor(donor): driver = login_database.login_neo4j_cloud() with driver.session() as session: log.info('Adding a new donor: {}'.format(donor)) cyph = """CREATE (:Person {{donor_name: '{}'}}) """.format(donor) session.run(cyph)
def run_example(): log.info('Step 1: First, clear the entire database, so we can start over') log.info("Running clear_all") people_names = [ ('Bob', 'Jones'), ('Nancy', 'Cooper'), ('Alice', 'Cooper'), ('Fred', 'Barnes'), ('Mary', 'Evans'), ('Marie', 'Curie'), ] driver = login_database.login_neo4j_cloud() with driver.session() as session: session.run("MATCH (n) DETACH DELETE n") log.info("Step 2: Add a few people") with driver.session() as session: log.info('Adding a few Person nodes') log.info('The cyph language is analagous to sql for neo4j') for first, last in people_names: cyph = "CREATE (n:Person {first_name:'%s', last_name: '%s'})" % ( first, last) session.run(cyph) log.info("Step 3: Get all of people in the DB:") cyph = """MATCH (p:Person) RETURN p.first_name as first_name, p.last_name as last_name """ result = session.run(cyph) print("People in database:") for record in result: print(record['first_name'], record['last_name']) log.info('Step 4: Create some relationships') COLORS = ['Blue', 'Green', 'Gray', 'Pink', 'Red'] for first, last in [("Alice", "Cooper"), ("Fred", "Barnes"), ("Marie", "Curie")]: cypher = """ MATCH (p1:Person {first_name:'%s', last_name:'%s'}) CREATE (p1)-[favorite:FAVORITE]->(p2:Color {name:'%s'}) RETURN p1 """ % (first, last, COLORS[random.randint(0, 4)]) session.run(cypher) for first, last in people_names: cyph = """ MATCH (p1:Person {first_name:'%s', last_name:'%s'}) -[:FAVORITE]->(favoriteColor) RETURN favoriteColor """ % (first, last) result = session.run(cyph) for rec in result: for val in rec.values(): if val: print( f'{first} {last} favorite color is: {val["name"]}')
def get_donors(self): """Returns a dictionary of all donors and their donations.""" donor_dict = {} driver = login_database.login_neo4j_cloud() with driver.session() as session: cyph = """ MATCH (d:Donor) RETURN d.name as name """ donors = session.run(cyph) for donor in donors: cyph = """ MATCH (d1 {name:'%s'}) -[:DONATED]->(donations) RETURN donations""" % donor['name'] donations = session.run(cyph) donation_list = [] for rec in donations: for donation in rec.values(): donation_list.append( (donation['amount'], donation['date'])) donor_dict[donor['name']] = [ donation[0] for donation in sorted( donation_list, key=lambda x: x[1], reverse=True) ] return donor_dict
def populate_donor_data(): """ Populate donor data """ log.info('Step 1: First, clear the entire database, so we can start over') log.info("Running clear_all") driver = login_database.login_neo4j_cloud() with driver.session() as session: session.run("MATCH (n) DETACH DELETE n") log.info("set some data for database") log.info("Step 2: Add a few people") with driver.session() as session: # Define our initial donor data donor_data = [('Jimmy Nguyen', 'Houston'), ('Steve Smith', 'Seattle'), ('Julia Norton', 'Portland'), ('Ed Johnson', 'Atlanta'), ('Elizabeth McBath', 'Austin'), ] for donor, city in donor_data: cyph = "CREATE (n:Donor {donor_name:'%s', city: '%s'})" % ( donor, city) session.run(cyph)
def clear_db(): log.info('Step 1: First, clear the entire database, so we can start over') log.info("Running clear_all") driver = login_database.login_neo4j_cloud() with driver.session() as session: session.run("MATCH (n) DETACH DELETE n")
def setup_data(): try: driver = login_database.login_neo4j_cloud() with driver.session() as session: # add sample data for d in sample_data: cs1 = ("first_name: '{}', " "last_name: '{}', " "email: '{}', " "phone: '{}', " "zip_code: '{}', " "donations: {}") cs2 = cs1.format( d['first_name'], d['last_name'], d['email'], d['phone'], d['zip_code'], d['donations'] ) cyph = "CREATE (d:Donor {{{}}})".format(cs2) session.run(cyph) except Exception as e: log.info(e)
def delete_donations(self, donor): # To delete this node, you must first delete its relationships. driver = login_database.login_neo4j_cloud() with driver.session() as session: cypher = """MATCH (donor:Donor{name:'%s'}) DETACH DELETE donor""" % (donor) result = session.run(cypher)
def populate_db(): log.info('Step 1: First, clear the entire database, so we can start over') log.info("Running clear_all") Main.clear_db() log.info("Step 2: Populating database with donors history") driver = login_database.login_neo4j_cloud() with driver.session() as session: log.info('Adding donors/donations') log.info('The cyph language is analagous to sql for neo4j') p1 = session.run("create (n:Donor {full_name: 'Bill Gates', donation: [100, 200, 300]})") p2 = session.run("create (n:Donor {full_name: 'Mike Dell', donation: [50, 200]})") p3 = session.run("create (n:Donor {full_name: 'Jeff Bezo', donation: [668.99, 1999]})") p4 = session.run("create (n:Donor {full_name: 'Harry Potter', donation: [88]})") l1 = session.run("create (n:Location {location: 'London'})") l2 = session.run("create (n:Location {location: 'Seattle'})") l3 = session.run("create (n:Location {location: 'Everett'})") l3 = session.run("create (n:Location {location: 'Redmond'})") for i in [('Bill Gates', 'Redmond'), ('Mike Dell', 'Seattle'), ('Jeff Bezo', 'Everett'), ('Harry Potter', 'London')]: session.run(""" MATCH (a:Donor {full_name: '%s'}) CREATE (a) -[r:LIVE_IN]-> (l:Location {location: '%s'}) RETURN type(r) """ % (i[0], i[1]) )
def update_donation(donor, old_donation, new_donation): """ Update donation amount """ log.info('Working with Neo4j update_donation function') log.info('Updating Donation record...') try: driver = login_database.login_neo4j_cloud() with driver.session() as session: donor_id = donor.replace(' ', '_').lower() try: log.info('Updating Donation amount') cyph = """MATCH (d:Donation { donor_id: '%s', donation_amount: '%s' }) SET d.donation_amount = '%s' RETURN d """ % (donor_id, str(int(old_donation)), new_donation) session.run(cyph) except Exception as e: log.info(f'Error updating Donation = {donor, old_donation}') log.info(e) except Exception as e: log.info(f'Error updating Donation = {donor, old_donation}') log.info(e) finally: log.info('Neo4j update_donation complete')
def drop_donors(): try: driver = login_database.login_neo4j_cloud() with driver.session() as session: session.run("MATCH (d) DETACH DELETE d") except Exception as e: log.info(e)
def get_donor_names(): """ Get donor names from database """ log.info('Working with Neo4j get_donor_names function') log.info('Querying Donor records...') try: driver = login_database.login_neo4j_cloud() with driver.session() as session: donor_names = [] cyph = """MATCH (d:Donor) RETURN d.donor_name as donor_name """ result = session.run(cyph) for record in result: donor_names.append(record['donor_name']) except Exception as e: log.info(f'Error retrieving Donors') log.info(e) finally: log.info('Neo4j get_donor_names complete') return donor_names
def letters_for_all(): driver = login_database.login_neo4j_cloud() mail = d.Group(driver) path_letters = os.getcwd() print(f"You chose to send letters for everyone. " f"The letters have been completed and you " f"can find them here: {path_letters}") mail.letters()
def get_session(self): if self.driver == None: self.driver = login_database.login_neo4j_cloud() print("Creating New Driver") else: print("Using Existing Driver") return self.driver.session()
def donor_detach_delete(): """ neo4j detach_delete """ log.info("Running clear_all") driver = login_database.login_neo4j_cloud() with driver.session() as session: session.run("MATCH (n) DETACH DELETE n")
def list_donors(): driver = login_database.login_neo4j_cloud() with driver.session() as session: donor_names = session.run( "match (n:Person) return n.first_name as first, n.last_name as last, count(*) order by last, first" ) for i in donor_names: print(i[0], i[1])
def create_donation(donor, amount): """ Add new donation to database """ log.info('Working with Neo4j create_donation function') log.info('Creating Donation record...') try: driver = login_database.login_neo4j_cloud() with driver.session() as session: donor_id = donor.replace(' ', '_').lower() cyph = "CREATE (d:Donation {donation_amount:'%s', donor_id:'%s'})" % ( amount, donor_id) session.run(cyph) log.info('Donation created.') cyph = """MATCH (d:Donation) RETURN d.donation_amount as donation_amount, d.donor_id as donor_id """ result = session.run(cyph) log.info('Create Donor relationship') cypher = """MATCH (p:Donor {id:'%s'}) CREATE (p)-[gave:GAVE]->(d:Donation {donation_amount:'%s', donor_id:'%s'}) RETURN p """ % (donor_id, amount, donor_id) session.run(cypher) log.info('Print donation relationships.') cyph = """MATCH (donor {donor_name:'%s', id:'%s'}) -[:GAVE]->(donationsGiven) RETURN donationsGiven """ % (donor, donor_id) result = session.run(cyph) print("{} has given:".format(donor)) for rec in result: for gave in rec.values(): print(gave) except Exception as e: log.info(f'Error creating = {donor, amount}') log.info(e) finally: log.info('Neo4j create_donation complete')
def send_letters(): driver = login_database.login_neo4j_cloud() with driver.session() as session: cyph = session.run( "match (n:Person) return n.first_name, n.last_name, count(*), sum(n.donation) as sum, avg(n.donation)" ) for i in cyph: with open('{}.txt'.format(' '.join([i[0], i[1]])), 'w') as donorfh: donorfh.write(send_thankyou_total(' '.join([i[0], i[1]]), i[3]))
def create_location(loc): log.info('Adding location to DB') driver = login_database.login_neo4j_cloud() with driver.session() as session: cyph = """MATCH (l:Location {location : '%s'}) RETURN l.location """ % (loc) result = session.run(cyph) if not Main.isResultRecord(result): session.run("""create (n:Location {location: '%s'})""" % loc)
def update_donations(donor, donation): driver = login_database.login_neo4j_cloud() with driver.session() as session: log.info('Updating donations') cyph = """ MATCH (person: Person {{donor_name: '{}'}}) CREATE (person) -[:DONATED]-> (d:Donations {{amount: {}}}) RETURN person """.format(donor, donation) session.run(cyph)
def rename_donations(self, old_name, new_name): if old_name == new_name: return driver = login_database.login_neo4j_cloud() with driver.session() as session: cypher = """MATCH (donor:Donor{name:'%s'})-[:GIFT]->(donation:Donation) SET donor.name='%s' RETURN donor""" % (old_name, new_name) result = session.run(cypher)
def more_choices(): driver = login_database.login_neo4j_cloud() mail = d.Group(driver) individual = d.Individual(driver) r = login_database.login_redis_cloud() while True: name = input('\nChoose an Option: \n' 'e - to exit\n' 'list - To see a list of names, or\n' 'Type a name to start your thank you letter >>') if name == 'e': return if name == 'list': mail.print_donors() else: print('\n''Ok, you want to write a letter for {}, ' 'lets see what we can do.'.format(name)) if mail.search(name) is None: yes_no = input('The name you entered is not in the database.' 'Would you like to add this name? y or n >>\n') if yes_no == 'n': return if yes_no == 'y': last_name = input(f"What is {name}'s last name?\n") email = input(f"What is {name}'s email?\n") telephone = input(f"What is {name}'s telephone #?\n") d.Individual.redis_add_new(r, name, last_name, telephone, email) else: return print(f"First confirm {name}'s information") individual.donor_verification(r, name) confirm_info = input("Does the donor info look ok? y or n >>\n") if confirm_info == 'n': update_redis(r, name) amount = input('\n''What is the donation amount? or ' '\'e\' to exit >') if amount == 'e': return try: if int(amount) <= 0: print('\nYou entered an invalid amount!!\n') return except ValueError: print('\nYou entered an invalid amount!!\n') return ValueError else: individual.add_donation(name, float(amount)) print(individual.thank_you(name, float(amount)))
def noe4j_read_all(): driver = login_database.login_neo4j_cloud() with driver.session() as session: log.info("Step 3: Get all of people in the DB:") cyph = """MATCH (p:Person) RETURN p.first_name as first_name, p.last_name as last_name """ result = session.run(cyph) print("People in database:") for record in result: print(record['first_name'], record['last_name'])
def add_donor_donation(): """ Adds new donor and donation, or adds donation to existing donor """ log.info("Step 4: Add Donor Update Donation") driver = login_database.login_neo4j_cloud() # name = input("Type donor first and last name: ") location = input("Type donor location: ") Main.create_location(location) try: don = float(input(" Donation in USD: ")) except ValueError: print(""" Donation must be in USD... Donor not added """) return() with driver.session() as session: cyph = """MATCH (p:Donor {full_name : '%s'}) RETURN p.full_name, p.donation """ % (name) result = session.run(cyph) if Main.isResultRecord(result): print("+++ {} in DB, adding donation".format(name)) for record in result: print(record['p.full_name'], record['p.donation']) cyph = """ MATCH (p:Donor {full_name : '%s'}) RETURN p.donation """ % (name) for i in session.run(cyph): d = i['p.donation'] d.append(don) cyph = """ MATCH (p:Donor {full_name : '%s'}) SET p.donation = %s RETURN p.full_name, p.donation """ % (name, d) result = session.run(cyph) else: print("+++ {} not in DB, creating new donor".format(name)) d = session.run("create (n:Donor {full_name: '%s', donation: [%s]})" % (name, don)) session.run(""" MATCH (a:Donor {full_name: '%s'}) CREATE (a) -[r:LIVE_IN]-> (l:Location {location: '%s'}) RETURN type(r) """ % (name, location) ) Main.print_greetings(Main.greetings(name, don))
def delete_donor(): """ Working with Donor table... """ driver = login_database.login_neo4j_cloud() name = input("Type donor to delete: ") log.info("Removing donor {} from database...".format(name)) with driver.session() as session: cyph = """MATCH (p:Donor {full_name : '%s'}) DELETE p """ % (name) result = session.run(cyph)
def add_donation(self, donor, amount): if not self.donor_exists(donor): self.add_donor(donor) driver = login_database.login_neo4j_cloud() with driver.session() as session: cyph = """MATCH (p:Donor{name:'%s'} ) CREATE (p)-[:GIFT]->(:Donation {amount:'%s'}) RETURN p """ % (donor, amount) result = session.run(cyph)
def create_report(): print('{:20} | {:15} | {:10} | {:15}'.format('Donor Name', 'Total Given', 'Num Gifts', 'Average Gift')) print('-' * 70) driver = login_database.login_neo4j_cloud() with driver.session() as session: cyph = session.run( "match (n:Person) return n.first_name, n.last_name, count(*), sum(n.donation) as sum, avg(n.donation) order by sum desc" ) for i in cyph: print('{:20} | {:15} | {:10} | {:15}'.format( ' '.join([i[0], i[1]]), i[2], i[3], i[4]))
def delete_donor(d): """ deletes donor """ try: driver = login_database.login_neo4j_cloud() with driver.session() as session: cypher = """ MATCH (d) WHERE ID(d) = %s DETACH DELETE d """ % (d.id) session.run(cypher) except Exception as e: log.info(e)
def test_delete_from_db(self): driver = login_database.login_neo4j_cloud() with driver.session() as session: cyph = "CREATE (n:Donor {name:'fred', date_added:'2019-04-07'})" session.run(cyph) self.mailroom.delete_from_db('fred') cyph = """ MATCH (d:Donor {name: 'fred'}) RETURN d.name as name """ self.assertEqual(session.run(cyph).value(), [])