|
| 1 | +from datetime import datetime |
| 2 | +from sqlalchemy.exc import OperationalError |
| 3 | + |
| 4 | +from config import app, db |
| 5 | +from models import Note, Person |
| 6 | + |
| 7 | +PEOPLE_NOTES = [ |
| 8 | + { |
| 9 | + "lname": "Fairy", |
| 10 | + "fname": "Tooth", |
| 11 | + "notes": [ |
| 12 | + ("I brush my teeth after each meal.", "2022-01-06 17:10:24"), |
| 13 | + ( |
| 14 | + "The other day a friend said, I have big teeth.", |
| 15 | + "2022-03-05 22:17:54", |
| 16 | + ), |
| 17 | + ("Do you pay per gram?", "2022-03-05 22:18:10"), |
| 18 | + ], |
| 19 | + }, |
| 20 | + { |
| 21 | + "lname": "Ruprecht", |
| 22 | + "fname": "Knecht", |
| 23 | + "notes": [ |
| 24 | + ( |
| 25 | + "I swear, I'll do better this year.", |
| 26 | + "2022-01-01 09:15:03", |
| 27 | + ), |
| 28 | + ( |
| 29 | + "Really! Only good deeds from now on!", |
| 30 | + "2022-02-06 13:09:21", |
| 31 | + ), |
| 32 | + ], |
| 33 | + }, |
| 34 | + { |
| 35 | + "lname": "Bunny", |
| 36 | + "fname": "Easter", |
| 37 | + "notes": [ |
| 38 | + ( |
| 39 | + "Please keep the current inflation rate in mind!", |
| 40 | + "2022-01-07 22:47:54", |
| 41 | + ), |
| 42 | + ("No need to hide the eggs this time.", "2022-04-06 13:03:17"), |
| 43 | + ], |
| 44 | + }, |
| 45 | +] |
| 46 | + |
| 47 | + |
| 48 | +def get_data_from_table(model): |
| 49 | + try: |
| 50 | + data = db.session.query(model).all() |
| 51 | + db.session.close() |
| 52 | + return data |
| 53 | + except OperationalError: |
| 54 | + return [] |
| 55 | + |
| 56 | + |
| 57 | +def create_database(db): |
| 58 | + db.create_all() |
| 59 | + for data in PEOPLE_NOTES: |
| 60 | + new_person = Person(lname=data.get("lname"), fname=data.get("fname")) |
| 61 | + for content, timestamp in data.get("notes", []): |
| 62 | + new_person.notes.append( |
| 63 | + Note( |
| 64 | + content=content, |
| 65 | + timestamp=datetime.strptime( |
| 66 | + timestamp, "%Y-%m-%d %H:%M:%S" |
| 67 | + ), |
| 68 | + ) |
| 69 | + ) |
| 70 | + db.session.add(new_person) |
| 71 | + db.session.commit() |
| 72 | + print("Created new database") |
| 73 | + |
| 74 | + |
| 75 | +def update_database(db, existing_people, existing_notes): |
| 76 | + db.drop_all() |
| 77 | + db.create_all() |
| 78 | + for person in existing_people: |
| 79 | + db.session.merge(person) |
| 80 | + for note in existing_notes: |
| 81 | + db.session.merge(note) |
| 82 | + db.session.commit() |
| 83 | + print("Updated existing database") |
| 84 | + |
| 85 | + |
| 86 | +with app.app_context(): |
| 87 | + existing_people = get_data_from_table(Person) |
| 88 | + existing_notes = get_data_from_table(Note) |
| 89 | + |
| 90 | + if not existing_people: |
| 91 | + create_database(db) |
| 92 | + else: |
| 93 | + update_database(db, existing_people, existing_notes) |
0 commit comments