Skip to content

Commit

Permalink
Merge pull request #18 from CSE2102-Fall24/Milestone6-ericfeaturebranch
Browse files Browse the repository at this point in the history
complete api and database connection
  • Loading branch information
eoa21004 authored Nov 7, 2024
2 parents 833f548 + 88cd05d commit 56c1d95
Show file tree
Hide file tree
Showing 4 changed files with 341 additions and 71 deletions.
188 changes: 188 additions & 0 deletions Backend/databasefunctions.py
Original file line number Diff line number Diff line change
@@ -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()


# -------------------------------------------------------------
52 changes: 25 additions & 27 deletions Backend/generateData.py → Backend/databaseinit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
Expand All @@ -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
Expand All @@ -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')
44 changes: 0 additions & 44 deletions Backend/everythingData.py

This file was deleted.

Loading

0 comments on commit 56c1d95

Please sign in to comment.