diff --git a/Backend/databasefunctions.py b/Backend/databasefunctions.py new file mode 100644 index 0000000..f0cecf4 --- /dev/null +++ b/Backend/databasefunctions.py @@ -0,0 +1,188 @@ +from contextlib import closing +import sqlite3 + +def connect_db(): + """Establish a connection to the SQLite database.""" + return sqlite3.connect('Projectdatabase.db') #this might change + +# ---------------------------------------------------------------------------------------------- insert functions + +def insert_user(name, age, location): + """Insert a new user into the accounts table.""" + with closing(connect_db()) as conn, conn: + cursor = conn.cursor() + cursor.execute( + '''INSERT INTO accounts (name, age, location) + VALUES (?, ?, ?)''', + (name, age, location) + ) + conn.commit() + return cursor.lastrowid + + +def insert_pet(name, age, gender, breed, type, location, photo_path=None): + """Insert a new pet into the pets table.""" + with closing(connect_db()) as conn, conn: + cursor = conn.cursor() + cursor.execute( + '''INSERT INTO pets (name, age, gender, breed, type, location, photo_path) + VALUES (?, ?, ?, ?, ?, ?, ?)''', + (name, age, gender, breed, type, location, photo_path) + ) + conn.commit() + return cursor.lastrowid + + +def insert_favorite(user_id, pet_id): + """Insert usere favorite pet into favorites table""" + with closing(connect_db()) as conn, conn: + cursor = conn.cursor() + cursor.execute( + '''INSERT INTO favorites (user_id, pet_id) + VALUES (?, ?)''', + (user_id, pet_id) + ) + conn.commit() + return cursor.lastrowid + +# ------------------------------------------------------------------------------------- remove functions + +def remove_user(user_id): + """Remove a pet from the accounts table.""" + with closing(connect_db()) as conn, conn: + cursor = conn.cursor() + cursor.execute( + '''DELETE FROM accounts + WHERE user_id = ?''', + (user_id,) + ) + conn.commit() + return cursor.rowcount + + +def remove_pet(pet_id): + """Remove a pet from the pets table.""" + with closing(connect_db()) as conn, conn: + cursor = conn.cursor() + cursor.execute( + '''DELETE FROM pets + WHERE pet_id = ?''', + (pet_id,) + ) + conn.commit() + return cursor.rowcount + + +def remove_favorite(user_id, pet_id): + """Remove a favorite row from the favorites table based on user_id and pet_id.""" + with closing(connect_db()) as conn: + cursor = conn.cursor() + + # Execute DELETE query to remove the row matching user_id and pet_id + cursor.execute(""" + DELETE FROM favorites + WHERE user_id = ? AND pet_id = ? + """, (user_id, pet_id)) + + conn.commit() + return cursor.rowcount # Returns the number of rows affected (should be 1 if successful) + +# ----------------------------------------------------------------------------------------------------------- change fucntions + + +def change_user_attributes(user_id, attribute, change): + """Update a user's attribute in the accounts table.""" + + # List of valid column names to avoid SQL injection + valid_columns = ['name', 'age', 'location'] # Add your valid column names here + + if attribute not in valid_columns: + raise ValueError("Invalid attribute name.") + + with closing(connect_db()) as conn: + cursor = conn.cursor() + + # Use the attribute directly, now it's safe since we validated it + cursor.execute(f""" + UPDATE accounts + SET {attribute} = ? + WHERE user_id = ? + """, (change, user_id)) + + conn.commit() + return fetch_user_by_id(user_id) + + +def change_pet_attributes(pet_id, attribute, change): + """Update a user's attribute in the accounts table.""" + + # List of valid column names to avoid SQL injection + valid_columns = ['name', 'age', 'location', 'breed', 'gender', 'type', 'photo_path'] # Add your valid column names here + + if attribute not in valid_columns: + raise ValueError("Invalid attribute name.") + + with closing(connect_db()) as conn: + cursor = conn.cursor() + + # Use the attribute directly, now it's safe since we validated it + cursor.execute(f""" + UPDATE pets + SET {attribute} = ? + WHERE pet_id = ? + """, (change, pet_id)) + + conn.commit() + return fetch_pet_by_id(pet_id) + +# ----------------------------------------------------------------------------------------------------------- fetch functions + + +def fetch_favorites_by_user(user_id): + """Fetch all favorite pets for a given user_id.""" + with closing(connect_db()) as conn: + cursor = conn.cursor() + + cursor.execute(""" + SELECT pets.* + FROM pets + INNER JOIN favorites ON pets.pet_id = favorites.pet_id + WHERE favorites.user_id = ? + """, (user_id,)) + + return cursor.fetchall() + + +def fetch_all_users(): + """Retrieve all users from the accounts table.""" + with closing(connect_db()) as conn: + cursor = conn.cursor() + cursor.execute("SELECT * FROM accounts") + return cursor.fetchall() + + +def fetch_all_pets(): + """Retrieve all pets from the pets table.""" + with closing(connect_db()) as conn: + cursor = conn.cursor() + cursor.execute("SELECT * FROM pets") + return cursor.fetchall() + + +def fetch_user_by_id(user_id): + """Retrieve a user by their account_id.""" + with closing(connect_db()) as conn: + cursor = conn.cursor() + cursor.execute("SELECT * FROM accounts WHERE user_id = ?", (user_id,)) + return cursor.fetchone() + + +def fetch_pet_by_id(pet_id): + """Retrieve a pet by their pet_id.""" + with closing(connect_db()) as conn: + cursor = conn.cursor() + cursor.execute("SELECT * FROM pets WHERE pet_id = ?", (pet_id,)) + return cursor.fetchone() + + +# ------------------------------------------------------------- diff --git a/Backend/generateData.py b/Backend/databaseinit.py similarity index 65% rename from Backend/generateData.py rename to Backend/databaseinit.py index 4df7a35..861c9a8 100644 --- a/Backend/generateData.py +++ b/Backend/databaseinit.py @@ -4,24 +4,20 @@ from contextlib import closing import os - - def populate_test_data(db_path): '''THE ACTUAL FUNCITON''' conn = sqlite3.connect(db_path) cursor = conn.cursor() - - + conn.execute("PRAGMA foreign_keys = ON") # Create tables cursor.executescript(''' - CREATE TABLE IF NOT EXISTS users ( + CREATE TABLE IF NOT EXISTS accounts ( user_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, - marital_status TEXT, - pet_preference TEXT, + location TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); @@ -31,32 +27,31 @@ def populate_test_data(db_path): age INTEGER, gender TEXT CHECK(gender IN ('male', 'female')), breed TEXT, - type TEXT CHECK(type IN ('dog', 'cat')), + type TEXT, location TEXT, photo_path TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); - CREATE TABLE IF NOT EXISTS user_tests ( - test_id INTEGER PRIMARY KEY AUTOINCREMENT, + + CREATE TABLE IF NOT EXISTS favorites ( + favorite_id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, - question TEXT, - answer TEXT, - FOREIGN KEY (user_id) REFERENCES users(user_id) + pet_id INTEGER, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); - ''') #ur welcome :) + ''') # Insert sample users cursor.executescript(''' - INSERT INTO users (name, age, marital_status, pet_preference) VALUES - ('Ben Ten', 28, 'single', 'dog'), - ('Spongebob Smith', 35, 'married', 'cat'), - ('Dipper Pines', 25, 'married', 'any'), - ('Emilia Kirej', 20, 'married', 'dog'); - + INSERT INTO accounts (name, age) VALUES + ('Ben Ten', 28), + ('Spongebob Smith', 35), + ('Dipper Pines', 25), + ('Emilia Kirej', 20); ''') - + # Insert sample pets cursor.executescript(''' INSERT INTO pets (name, age, gender, breed, type, location, photo_path) VALUES @@ -66,12 +61,15 @@ def populate_test_data(db_path): ('Monster', 5, 'female', 'Maine Coon', 'cat', 'Houston, TX', 'images/monster.jpg'); ''') + # Insert sample favorites + cursor.executescript(''' + INSERT INTO favorites (user_id, pet_id) VALUES + (2, 4), + (1, 2); + ''') + conn.commit() conn.close() - - - -#populate_test_data('/home/sus98/2102/proj/cse2102-fall24-Team51/Backend/testData.db') - - +if __name__ == "__main__": + populate_test_data('Projectdatabase.db') diff --git a/Backend/everythingData.py b/Backend/everythingData.py deleted file mode 100644 index 32b0c3f..0000000 --- a/Backend/everythingData.py +++ /dev/null @@ -1,44 +0,0 @@ -from contextlib import closing -import sqlite3 - -def connect_db(): - """Establish a connection to the SQLite database.""" - return sqlite3.connect('/home/sus98/2102/proj/cse2102-fall24-Team51/Backend/testData.db') #this might change - -def insert_user(name, age, marital_status, pet_preference): - """Insert a new user into the users table.""" - with closing(connect_db()) as conn, conn: - cursor = conn.cursor() - cursor.execute( - '''INSERT INTO users (name, age, marital_status, pet_preference) - VALUES (?, ?, ?, ?)''', - (name, age, marital_status, pet_preference) - ) - conn.commit() - return cursor.lastrowid - -def insert_pet(name, age, gender, breed, type, location, picture=None): - """Insert a new pet into the pets table.""" - with closing(connect_db()) as conn, conn: - cursor = conn.cursor() - cursor.execute( - '''INSERT INTO pets (name, age, gender, breed, type, location, picture) - VALUES (?, ?, ?, ?, ?, ?, ?)''', - (name, age, gender, breed, type, location, picture) - ) - conn.commit() - return cursor.lastrowid - -def fetch_all_pets(): - """Retrieve all pets from the pets table.""" - with closing(connect_db()) as conn: - cursor = conn.cursor() - cursor.execute("SELECT * FROM pets") - return cursor.fetchall() - -def fetch_user_by_id(user_id): - """Retrieve a user by their user_id.""" - with closing(connect_db()) as conn: - cursor = conn.cursor() - cursor.execute("SELECT * FROM users WHERE user_id = ?", (user_id,)) - return cursor.fetchone() diff --git a/Backend/main.py b/Backend/main.py new file mode 100644 index 0000000..913cd46 --- /dev/null +++ b/Backend/main.py @@ -0,0 +1,128 @@ +""" +This module provides functions for HTTP communication and +route functions +""" +import sqlite3 +import databasefunctions +from flask import Flask, request, jsonify +from petfuc import get_random_pet +from userfuc import add_user_faviorte, remove_user_faviorte, replace_user_location +app = Flask(__name__) + +# ----------------------------------------------------------------------------------------- + +@app.route("/add_newuser", methods=["POST"]) +def add_newuser(): + """ + Adds new user to database + """ + data = request.get_json() + newuser_id = databasefunctions.insert_user(data.get("name"), data.get("age"), data.get("location")) + + return jsonify({'user_id': newuser_id}), 200 + +@app.route("/add_newpet", methods=["POST"]) +def add_newpet(): + """ + Adds new pet to database + """ + data = request.get_json() + newpet_id = databasefunctions.insert_pet(data.get("name"), data.get("age"), + data.get("gender"), data.get("breed"), data.get("type"), + data.get("location"), data.get("photo_path")) + + return jsonify({'pet_id': newpet_id}), 200 + + +@app.route("/add_newfavorite", methods=["POST"]) +def add_newfavorite(): + """ + Adds new user favorite to database + """ + data = request.get_json() + newfavorite_id = databasefunctions.insert_favorite(data.get("user_id"), data.get("pet_id")) + + return jsonify({'faviorte_id': newfavorite_id}), 200 + + + +#------------------------------------------------------------------------------------------------ + +@app.route("/remove_user", methods=["DELETE"]) +def removeuser(): + """ + Remove user from database + """ + data = request.get_json() + userid = data.get("user_id") + roweffected = databasefunctions.remove_user(userid) + + return (f"{roweffected}, row was deleted in user table"), 200 + + +@app.route("/remove_pet", methods=["DELETE"]) +def removepet(): + """ + Remove pet from database + """ + data = request.get_json() + petid = data.get("petid") + roweffected = databasefunctions.remove_pet(petid) + + return (f"{roweffected}, row was deleted in pet table"), 200 + + +@app.route("/remove_favorite", methods=["DELETE"]) +def removefavorite(): + """ + Remove favorite from database + """ + data = request.get_json() + roweffected = databasefunctions.remove_favorite(data.get("user_id"),data.get("pet_id")) + + return (f"{roweffected}, row was deleted in the favorite table"), 200 + +# --------------------------------------------------------------------- + + +@app.route("/fetch_pet", methods=["POST"]) +def fetch_pet(): + """ + fetch pet from database + """ + data = request.get_json() + petid = data.get("pet_id") + users_row = databasefunctions.fetch_pet_by_id(petid) + + return jsonify(users_row), 200 + + +@app.route("/fetch_user", methods=["POST"]) +def fetch_user(): + """ + fetch user from database + """ + data = request.get_json() + userid = data.get("user_id") + users_row = databasefunctions.fetch_user_by_id(userid) + + return jsonify(users_row), 200 + + +@app.route("/fetch_favorited_pets", methods=["POST"]) +def fetch_favorite_pet(): + """ + fetches all pets favorited by a user + """ + data = request.get_json() + userid = data.get("user_id") + favorited_pets = databasefunctions.fetch_favorites_by_user(userid) + + return jsonify(favorited_pets), 200 + + +# --------------------------------------------------------------- + + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=5000, debug=True)