THE TABLE

import os
import json
import datetime
from datetime import datetime
from sqlalchemy.exc import IntegrityError
from werkzeug.security import generate_password_hash, check_password_hash
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import sqlite3

app = Flask(__name__)
database = 'sqlite:///sqlite.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = database
app.config['SECRET_KEY'] = 'SECRET_KEY'
db = SQLAlchemy()
Migrate(app, db)

db.init_app(app)

class Album(db.Model):
    __tablename__ = 'albums'
    id = db.Column(db.Integer, primary_key=True)
    album = db.Column(db.String(255), nullable=False)
    artist = db.Column(db.String(255), nullable=False)
    year = db.Column(db.Integer, nullable=False)

    def __init__(self, album, artist, year):
        self.album = album
        self.artist = artist
        self.year = year

    def __str__(self):
        return json.dumps(self.read())

    def create(self):
        db.session.add(self)
        db.session.commit()
        return self

    def read(self):
        return {'album': self.album, 'artist': self.artist, 'year': self.year}

    def update(self, album, artist, year):
        self.album = album
        self.artist = artist
        self.year = year
        db.session.commit()
        return self

    def delete(self):
        db.session.delete(self)
        db.session.commit()
        return None

def initAlbums():
    with app.app_context():
        db.create_all()

        with open(os.path.join("files", "album.json"), "r") as f:
            data = json.load(f)
            for album_name, album_id in data["Album ID"].items():
                album_artist = data["Creator"][album_name]
                album_year = data["Year"][album_name]

                # check if album already exists in database
                album = Album.query.filter_by(album=album_name, artist=album_artist, year=album_year).first()
                if album is None:
                    album = Album(album=album_name, artist=album_artist, year=album_year)
                    album.create()

        db.session.commit()

initAlbums()
database = 'instance/sqlite.db'

def create(database):
    album = input("Enter the name of the album:")
    year = input("Enter the year it was created:")
    artist = input("Enter the name of the creator:")
    
    conn = sqlite3.connect(database)

    cursor = conn.cursor()

    try:
        cursor.execute("INSERT INTO albums (album, year, artist) VALUES (?, ?, ?)", (album, year, artist))
        
        conn.commit()
        print(f"A new album record {album} has been created")
                
    except sqlite3.Error as error:
        print("Error while executing the INSERT:", error)


    cursor.close()
    conn.close()

def read(database):
    conn = sqlite3.connect(database)
    cursor = conn.cursor()
    
    results = cursor.execute('SELECT * FROM albums').fetchall()

    if len(results) == 0:
        print("Table is empty")
    else:
        for row in results:
            print(row)

    cursor.close()
    conn.close()
    
def update(database):
    album = input("Enter album name to update")
    year = input("Enter updated year")
    if len(year) < 2:
        message = "doesn't exist"
        year = '1000 bc'
    else:
        message = "successfully updated"

    conn = sqlite3.connect(database)

    cursor = conn.cursor()

    try:
        cursor.execute("UPDATE albums SET year = ? WHERE album = ?", (year, album))
        if cursor.rowcount == 0:
            print(f"No album {album} was found in the table")
        else:
            print(f"The row with {year} the year has been {message}")
            conn.commit()
    except sqlite3.Error as error:
        print("Error while executing the UPDATE:", error)
        
    
    cursor.close()
    conn.close()
    

def delete(database):
    album = input("Enter album to delete")

    conn = sqlite3.connect(database)

    cursor = conn.cursor()
    
    try:
        cursor.execute("DELETE FROM albums WHERE album = ?", (album,))
        if cursor.rowcount == 0:
            print(f"No album {album} was not found in the table")
        else:
            print(f"The row with album {album} was successfully deleted")
        conn.commit()
    except sqlite3.Error as error:
        print("Error while executing the DELETE:", error)
        
    cursor.close()
    conn.close()
def menu(database):
    operation = input("Enter: (C)reate (R)ead (U)pdate or (D)elete")
    if operation.lower() == 'c':
        create(database)
    elif operation.lower() == 'r':
        read(database)
    elif operation.lower() == 'u':
        update(database)
    elif operation.lower() == 'd':
        delete(database)
    elif len(operation)==0: 
        return
    else:
        print("Please enter c, r, u, or d") 
    menu(database) 
        
try:
    menu(database) 
except:
    print("Perform Jupyter 'Run All' prior to starting menu")
A new album record Toys in the Attic has been created