From 0303db3a00b6fe52d2841d095891f92a7826fbc9 Mon Sep 17 00:00:00 2001
From: Navin Chandra <nc01009@surrey.ac.uk>
Date: Mon, 6 May 2024 04:15:52 +0530
Subject: [PATCH] added docker related code

---
 admins_service/main.py      |  72 +++++----
 bikes_service/__main.py     | 286 ++++++++++++++++++++++++++++++++++++
 bikes_service/main.py       | 112 ++++++++------
 rentals_service/main.py     |  81 +++++-----
 reviews_service/main.py     |  71 +++++----
 sql_files/common_insert.sql |  19 +++
 sql_files/table_schema.sql  |  62 ++++++++
 users_service/main.py       |  79 +++++-----
 8 files changed, 605 insertions(+), 177 deletions(-)
 create mode 100644 bikes_service/__main.py
 create mode 100644 sql_files/common_insert.sql
 create mode 100644 sql_files/table_schema.sql

diff --git a/admins_service/main.py b/admins_service/main.py
index 5bfd693..a75efda 100644
--- a/admins_service/main.py
+++ b/admins_service/main.py
@@ -2,6 +2,7 @@ from fastapi import FastAPI, HTTPException
 from pydantic import BaseModel
 from fastapi.middleware.cors import CORSMiddleware
 import sqlite3
+import mysql.connector   
 from pathlib import Path
 from typing import Optional, Tuple, List
 
@@ -16,37 +17,46 @@ app.add_middleware(
     allow_headers=["*"],
 )
 
-# SQLite connection
-# SQLite connection
+# # SQLite connection
+# # SQLite connection
+# # parent_directory = Path(__file__).resolve().parent.parent
+# # db_file_path = parent_directory / "my_ride.db"
+# # # print(db_file_path)
+
 # parent_directory = Path(__file__).resolve().parent.parent
+# # Specify the path to the SQLite database file in the data directory
 # db_file_path = parent_directory / "my_ride.db"
-# # print(db_file_path)
-
-parent_directory = Path(__file__).resolve().parent.parent
-# Specify the path to the SQLite database file in the data directory
-db_file_path = parent_directory / "my_ride.db"
-
-# Check if the database file exists
-if not db_file_path.exists():
-    # If the database file doesn't exist, use a local database file from the same location
-    local_db_file_path = Path(__file__).resolve().parent / "local_bike.db"
-    db_file_path = local_db_file_path
-
-conn = sqlite3.connect(db_file_path)
-
-cursor = conn.cursor()
-
-# Create the Admins table if it doesn't exist
-cursor.execute('''
-    CREATE TABLE IF NOT EXISTS Admins (
-        admin_id INTEGER PRIMARY KEY,
-        username TEXT,
-        password TEXT,
-        email TEXT,
-        phone_number TEXT
-    )
-''')
-conn.commit()
+
+# # Check if the database file exists
+# if not db_file_path.exists():
+#     # If the database file doesn't exist, use a local database file from the same location
+#     local_db_file_path = Path(__file__).resolve().parent / "local_bike.db"
+#     db_file_path = local_db_file_path
+
+# conn = sqlite3.connect(db_file_path)
+
+# cursor = conn.cursor()
+
+db_connection = mysql.connector.connect(
+    host='database_mysql',  # or '127.0.0.1' for IPv4 loopback
+    port='3306',  # Specify the port number here
+    user='root',
+    password='root_password',
+    database='your_database'
+)
+cursor = db_connection.cursor()
+
+# # Create the Admins table if it doesn't exist
+# cursor.execute('''
+#     CREATE TABLE IF NOT EXISTS Admins (
+#         admin_id INTEGER PRIMARY KEY,
+#         username TEXT,
+#         password TEXT,
+#         email TEXT,
+#         phone_number TEXT
+#     )
+# ''')
+# conn.commit()
 
 
 # Admin model
@@ -74,11 +84,11 @@ async def create_admin(admin: Admin):
     cursor.execute('''
         INSERT INTO Admins 
         (username, password, email, phone_number) 
-        VALUES (?, ?, ?, ?)
+        VALUES (%s, %s, %s, %s)
     ''', (
         admin.username, admin.password, admin.email, admin.phone_number
     ))
-    conn.commit()
+    db_connection.commit()
     return AdminResponse(
         username=admin.username,
         email=admin.email,
diff --git a/bikes_service/__main.py b/bikes_service/__main.py
new file mode 100644
index 0000000..9ff0fc4
--- /dev/null
+++ b/bikes_service/__main.py
@@ -0,0 +1,286 @@
+from fastapi import FastAPI, HTTPException
+from pydantic import BaseModel
+from fastapi.middleware.cors import CORSMiddleware
+from typing import List
+import sqlite3
+from pathlib import Path
+from typing import Optional
+import mysql.connector      
+
+app = FastAPI()
+
+# Allow requests from all origins
+app.add_middleware(
+    CORSMiddleware,
+    allow_origins=["*"],
+    allow_credentials=True,
+    allow_methods=["GET", "POST", "PUT", "DELETE"],
+    allow_headers=["*"],
+)
+
+######################### SQLite connection ########################
+# conn = sqlite3.connect('bikes.db')
+
+# Get the path to the parent directory of your FastAPI application
+# parent_directory = Path(__file__).resolve().parent.parent
+# # print(parent_directory)
+
+# # Specify the path to the SQLite database file in the data directory
+# db_file_path = parent_directory / "my_ride.db"
+
+# # Check if the database file exists
+# if not db_file_path.exists():
+#     # If the database file doesn't exist, use a local database file from the same location
+#     local_db_file_path = Path(__file__).resolve().parent / "local_bike.db"
+#     db_file_path = local_db_file_path
+
+# # print(db_file_path)
+# conn = sqlite3.connect(db_file_path)
+
+# cursor = conn.cursor()
+######################### SQLite connection ##########################
+######################### mysql connectivity #########################
+
+# MySQL connection
+# db_connection = mysql.connector.connect(
+#     host="localhost",  # Use the service name defined in docker-compose.yml
+#     user="your_username",
+#     password="your_password",
+#     database="your_database"
+# )
+db_connection = mysql.connector.connect(
+    host='localhost',  # or '127.0.0.1' for IPv4 loopback
+    port='3306',  # Specify the port number here
+    user='root',
+    password='root_password',
+    database='your_database'
+)
+
+cursor = db_connection.cursor()
+
+######################### mysql connectivity #########################
+
+# # Bike model
+# class Bike(BaseModel):
+#     model: str
+#     status: Optional[str]
+#     location: str
+#     condition: str
+#     price_per_hour: float
+#     last_maintenance_date: str
+#     maintenance_history: str
+
+
+# class BikeResponse(BaseModel):
+#     id: int
+#     model: str
+#     status: Optional[str]
+#     location: str
+#     condition: str
+#     price_per_hour: float
+#     last_maintenance_date: str
+#     maintenance_history: str
+
+# Bike model
+class Bike(BaseModel):
+    bike_id: int
+    model: str
+    bike_status: Optional[str]
+    current_location: str
+    bike_condition: str
+    price_per_hour: float
+    last_maintenance_date: str
+    maintenance_history: str
+
+
+class BikeResponse(BaseModel):
+    bike_id: int
+    model: str
+    bike_status: Optional[str]
+    current_location: str
+    bike_condition: str
+    price_per_hour: float
+    last_maintenance_date: str
+    maintenance_history: str
+
+
+# # Routes
+# @app.post("/bikes/", response_model=Bike)
+# async def create_bike(bike: Bike):
+#     cursor.execute('''
+#         INSERT INTO Bikes 
+#         (model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history) 
+#         VALUES (?, ?, ?, ?, ?, ?, ?)
+#     ''', (
+#         bike.model, bike.bike_status, bike.current_location, bike.bike_condition,
+#         bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history
+#     ))
+#     conn.commit()
+#     return bike
+
+
+
+# @app.get("/bikes/", response_model=List[BikeResponse])
+# async def read_bikes():
+#     cursor.execute('SELECT * FROM Bikes')
+#     bikes = cursor.fetchall()
+#     bike_objects = []
+#     for bike in bikes:
+#         bike_obj = BikeResponse(
+#             id=bike[0],
+#             model=bike[1],
+#             status=bike[2],
+#             location=bike[3],
+#             condition=bike[4],
+#             price_per_hour=bike[5],
+#             last_maintenance_date=bike[6],
+#             maintenance_history=bike[7]
+#         )
+#         bike_objects.append(bike_obj)
+#     return bike_objects
+
+
+# # Routes
+# @app.post("/bikes/", response_model=Bike)
+# async def create_bike(bike: Bike):
+#     cursor.execute('''
+#         INSERT INTO Bikes 
+#         (bike_id, model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history) 
+#         VALUES (?, ?, ?, ?, ?, ?, ?)
+#     ''', (
+#         bike.bike_id, bike.model, bike.bike_status, bike.current_location, bike.bike_condition,
+#         bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history
+#     ))
+#     conn.commit()
+#     return bike
+
+
+
+# @app.post("/bikes/", response_model=Bike)
+# async def create_bike(bike: Bike):
+#     try:
+#         # Cast price_per_hour to float
+#         bike.price_per_hour = float(bike.price_per_hour)
+
+#         sql_statement = '''
+#             INSERT INTO Bikes 
+#             (bike_id, model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history) 
+#             VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+#         '''
+#         values = (
+#             bike.bike_id, bike.model, bike.bike_status, bike.current_location, bike.bike_condition,
+#             bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history
+#         )
+#         print("Executing SQL statement:", sql_statement)
+#         print("Values:", values)
+        
+#         cursor.execute(sql_statement, values)
+#         db_connection.commit()
+#         return bike
+#     except Exception as e:
+#         # Log the exception or print it for debugging
+#         print("An error occurred during the POST request:", e)
+#         # Raise an HTTPException with a 500 Internal Server Error status code
+#         raise HTTPException(status_code=500, detail="Internal Server Error")
+
+@app.post("/bikes/", response_model=Bike)
+async def create_bike(bike: Bike):
+    try:
+        # Cast price_per_hour to float
+        bike.price_per_hour = float(bike.price_per_hour)
+
+        # Remove trailing whitespaces from the string fields
+        model = bike.model.strip()
+        current_location = bike.current_location.strip()
+        bike_condition = bike.bike_condition.strip()
+        last_maintenance_date = bike.last_maintenance_date.strip()
+        maintenance_history = bike.maintenance_history.strip()
+
+        # Remove trailing commas from the string fields
+        model = model.rstrip(',')
+        current_location = current_location.rstrip(',')
+        bike_condition = bike_condition.rstrip(',')
+        maintenance_history = maintenance_history.rstrip(',')
+
+        sql_statement = '''
+            INSERT INTO Bikes 
+            (bike_id, model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history) 
+            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+        '''
+        values = (
+            bike.bike_id, model, bike.bike_status, current_location, bike_condition,
+            bike.price_per_hour, last_maintenance_date, maintenance_history
+        )
+        print("Executing SQL statement:", sql_statement)
+        print("Values:", values)
+        
+        cursor.execute(sql_statement, values)
+        db_connection.commit()
+        return bike
+    except Exception as e:
+        # Log the exception or print it for debugging
+        print("An error occurred during the POST request:", e)
+        # Raise an HTTPException with a 500 Internal Server Error status code
+        raise HTTPException(status_code=500, detail="Internal Server Error")
+
+
+@app.get("/bikes/", response_model=List[BikeResponse])
+async def read_bikes():
+    cursor.execute('SELECT * FROM Bikes')
+    bikes = cursor.fetchall()
+    bike_objects = []
+    for bike in bikes:
+        bike_obj = BikeResponse(
+            bike_id=bike[0],
+            model=bike[1],
+            bike_status=bike[2],
+            current_location=bike[3],
+            bike_condition=bike[4],
+            price_per_hour=bike[5],
+            last_maintenance_date=str(bike[6]),  # Convert date to string
+            maintenance_history=bike[7]
+        )
+        bike_objects.append(bike_obj)
+    return bike_objects
+
+@app.get("/bikes/{bike_id}", response_model=Bike)
+async def read_bike(bike_id: int):
+    cursor.execute('SELECT * FROM Bikes WHERE bike_id = ?', (bike_id,))
+    bike = cursor.fetchone()
+    if bike is None:
+        raise HTTPException(status_code=404, detail="Bike not found")
+    
+    # Create a Bike object from the fetched data
+    bike_obj = Bike(
+        model=bike[1],
+        status=bike[2],
+        location=bike[3],
+        condition=bike[4],
+        price_per_hour=bike[5],
+        last_maintenance_date=bike[6],
+        maintenance_history=bike[7]
+    )
+    
+    return bike_obj
+
+
+@app.put("/bikes/{bike_id}", response_model=Bike)
+async def update_bike(bike_id: int, bike: Bike):
+    cursor.execute('''
+        UPDATE Bikes 
+        SET model = ?, status = ?, location = ?, condition = ?, 
+        price_per_hour = ?, last_maintenance_date = ?, maintenance_history = ?
+        WHERE bike_id = ?
+    ''', (
+        bike.model, bike.status, bike.location, bike.condition,
+        bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history, bike_id
+    ))
+    conn.commit()
+    return bike
+
+
+@app.delete("/bikes/{bike_id}")
+async def delete_bike(bike_id: int):
+    cursor.execute('DELETE FROM Bikes WHERE bike_id = ?', (bike_id,))
+    conn.commit()
+    return {"message": "Bike deleted successfully"}
diff --git a/bikes_service/main.py b/bikes_service/main.py
index 3db3954..28103db 100644
--- a/bikes_service/main.py
+++ b/bikes_service/main.py
@@ -1,3 +1,4 @@
+
 from fastapi import FastAPI, HTTPException
 from pydantic import BaseModel
 from fastapi.middleware.cors import CORSMiddleware
@@ -5,6 +6,7 @@ from typing import List
 import sqlite3
 from pathlib import Path
 from typing import Optional
+import mysql.connector      
 
 app = FastAPI()
 
@@ -17,44 +19,48 @@ app.add_middleware(
     allow_headers=["*"],
 )
 
-# SQLite connection
-# conn = sqlite3.connect('bikes.db')
-# Get the path to the parent directory of your FastAPI application
-parent_directory = Path(__file__).resolve().parent.parent
-# print(parent_directory)
-
-# Specify the path to the SQLite database file in the data directory
-db_file_path = parent_directory / "my_ride.db"
-
-# Check if the database file exists
-if not db_file_path.exists():
-    # If the database file doesn't exist, use a local database file from the same location
-    local_db_file_path = Path(__file__).resolve().parent / "local_bike.db"
-    db_file_path = local_db_file_path
-
-# print(db_file_path)
-conn = sqlite3.connect(db_file_path)
 
-cursor = conn.cursor()
+# db_connection = mysql.connector.connect(
+#     host="localhost",  # Use the service name defined in docker-compose.yml
+#     user="your_username",
+#     password="your_password",
+#     database="your_database"
+# )
+# db_connection = mysql.connector.connect(
+#     host='localhost',  # or '127.0.0.1' for IPv4 loopback
+#     port='3306',  # Specify the port number here
+#     user='root',
+#     password='root_password',
+#     database='your_database'
+# )
+
+db_connection = mysql.connector.connect(
+    host='database_mysql',  # or '127.0.0.1' for IPv4 loopback
+    port='3306',  # Specify the port number here
+    user='root',
+    password='root_password',
+    database='your_database'
+)
+cursor = db_connection.cursor()
 
 
 # Bike model
 class Bike(BaseModel):
     model: str
-    status: Optional[str]
-    location: str
-    condition: str
+    bike_status: Optional[str]
+    current_location: str
+    bike_condition: str
     price_per_hour: float
     last_maintenance_date: str
     maintenance_history: str
 
 
 class BikeResponse(BaseModel):
-    id: int
+    bike_id: int
     model: str
-    status: Optional[str]
-    location: str
-    condition: str
+    bike_status: Optional[str]
+    current_location: str
+    bike_condition: str
     price_per_hour: float
     last_maintenance_date: str
     maintenance_history: str
@@ -63,18 +69,35 @@ class BikeResponse(BaseModel):
 # Routes
 @app.post("/bikes/", response_model=Bike)
 async def create_bike(bike: Bike):
-    cursor.execute('''
-        INSERT INTO Bikes 
-        (model, status, location, condition, price_per_hour, last_maintenance_date, maintenance_history) 
-        VALUES (?, ?, ?, ?, ?, ?, ?)
-    ''', (
-        bike.model, bike.status, bike.location, bike.condition,
-        bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history
-    ))
-    conn.commit()
-    return bike
-
-
+    try:
+        # Cast price_per_hour to float
+        bike.price_per_hour = float(bike.price_per_hour)
+
+        sql_statement = '''
+            INSERT INTO Bikes 
+            (model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history) 
+            VALUES (%s, %s, %s, %s, %s, %s, %s)
+        '''
+        values = (
+            bike.model, bike.bike_status, bike.current_location, bike.bike_condition,
+            bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history
+        )
+        print("Executing SQL statement:", sql_statement)
+        print("Values:", values)
+        
+        cursor.execute(sql_statement, values)
+        db_connection.commit()
+        return bike
+    except mysql.connector.Error as e:
+        # Log the MySQL error for debugging
+        print("MySQL Error:", e)
+        # Raise an HTTPException with a 500 Internal Server Error status code
+        raise HTTPException(status_code=500, detail="Internal Server Error")
+    except Exception as e:
+        # Log other exceptions for debugging
+        print("An error occurred during the POST request:", e)
+        # Raise an HTTPException with a 500 Internal Server Error status code
+        raise HTTPException(status_code=500, detail="Internal Server Error")
 
 @app.get("/bikes/", response_model=List[BikeResponse])
 async def read_bikes():
@@ -83,13 +106,13 @@ async def read_bikes():
     bike_objects = []
     for bike in bikes:
         bike_obj = BikeResponse(
-            id=bike[0],
+            bike_id=bike[0],
             model=bike[1],
-            status=bike[2],
-            location=bike[3],
-            condition=bike[4],
+            bike_status=bike[2],
+            current_location=bike[3],
+            bike_condition=bike[4],
             price_per_hour=bike[5],
-            last_maintenance_date=bike[6],
+            last_maintenance_date=str(bike[6]),  # Convert date to string
             maintenance_history=bike[7]
         )
         bike_objects.append(bike_obj)
@@ -128,12 +151,13 @@ async def update_bike(bike_id: int, bike: Bike):
         bike.model, bike.status, bike.location, bike.condition,
         bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history, bike_id
     ))
-    conn.commit()
+    db_connection.commit()
     return bike
 
 
 @app.delete("/bikes/{bike_id}")
 async def delete_bike(bike_id: int):
     cursor.execute('DELETE FROM Bikes WHERE bike_id = ?', (bike_id,))
-    conn.commit()
+    db_connection.commit()
     return {"message": "Bike deleted successfully"}
+
diff --git a/rentals_service/main.py b/rentals_service/main.py
index ebeb17d..0b12d38 100644
--- a/rentals_service/main.py
+++ b/rentals_service/main.py
@@ -6,6 +6,7 @@ import sqlite3
 from pathlib import Path
 from typing import Optional
 from fastapi import HTTPException
+import mysql.connector   
 
 app = FastAPI()
 
@@ -18,38 +19,46 @@ app.add_middleware(
     allow_headers=["*"],
 )
 
-# SQLite connection
-parent_directory = Path(__file__).resolve().parent.parent
-db_file_path = parent_directory / "my_ride.db"
-# print(db_file_path)
-conn = sqlite3.connect(db_file_path)
-
-
-cursor = conn.cursor()
-
-# Create the Rentals table if it doesn't exist
-cursor.execute('''
-    CREATE TABLE IF NOT EXISTS Rentals (
-        rental_id INTEGER PRIMARY KEY,
-        id INT,
-        user_id INT,
-        bike_id INT,
-        year INT,
-        hour INT,
-        season INT,
-        holiday BOOLEAN,
-        workingday BOOLEAN,
-        weather INT,
-        temp DECIMAL(5, 2),
-        atemp DECIMAL(5, 2),
-        humidity DECIMAL(5, 2),
-        windspeed DECIMAL(5, 2),
-        count INT,
-        FOREIGN KEY (user_id) REFERENCES Users(user_id),
-        FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id)
-    )
-''')
-conn.commit()
+# # SQLite connection
+# parent_directory = Path(__file__).resolve().parent.parent
+# db_file_path = parent_directory / "my_ride.db"
+# # print(db_file_path)
+# conn = sqlite3.connect(db_file_path)
+# cursor = conn.cursor()
+
+db_connection = mysql.connector.connect(
+    host='database_mysql',  # or '127.0.0.1' for IPv4 loopback
+    port='3306',  # Specify the port number here
+    user='root',
+    password='root_password',
+    database='your_database'
+)
+
+cursor = db_connection.cursor()
+
+# # Create the Rentals table if it doesn't exist
+# cursor.execute('''
+#     CREATE TABLE IF NOT EXISTS Rentals (
+#         rental_id INTEGER PRIMARY KEY,
+#         id INT,
+#         user_id INT,
+#         bike_id INT,
+#         year INT,
+#         hour INT,
+#         season INT,
+#         holiday BOOLEAN,
+#         workingday BOOLEAN,
+#         weather INT,
+#         temp DECIMAL(5, 2),
+#         atemp DECIMAL(5, 2),
+#         humidity DECIMAL(5, 2),
+#         windspeed DECIMAL(5, 2),
+#         count INT,
+#         FOREIGN KEY (user_id) REFERENCES Users(user_id),
+#         FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id)
+#     )
+# ''')
+# conn.commit()
 
 
 # Rental model
@@ -133,13 +142,13 @@ async def create_rental(rental: Rental):
         cursor.execute('''
             INSERT INTO Rentals 
             (user_id, bike_id, year, hour, season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count) 
-            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
         ''', (
             rental.user_id, rental.bike_id, rental.year, rental.hour,
             rental.season, rental.holiday, rental.workingday, rental.weather,
             rental.temp, rental.atemp, rental.humidity, rental.windspeed, rental.count
         ))
-        conn.commit()
+        db_connection.commit()
         # Get the auto-generated id of the new rental
         rental_id = cursor.lastrowid
         # Return the created rental with the generated id
@@ -218,12 +227,12 @@ async def update_rental(rental_id: int, rental: Rental):
         rental.temp, rental.atemp, rental.humidity, rental.windspeed,
         rental.count, rental_id
     ))
-    conn.commit()
+    db_connection.commit()
     return rental
 
 
 @app.delete("/rentals/{rental_id}")
 async def delete_rental(rental_id: int):
     cursor.execute('DELETE FROM Rentals WHERE rental_id = ?', (rental_id,))
-    conn.commit()
+    db_connection.commit()
     return {"message": "Rental deleted successfully"}
diff --git a/reviews_service/main.py b/reviews_service/main.py
index ce085ac..e27a452 100644
--- a/reviews_service/main.py
+++ b/reviews_service/main.py
@@ -5,6 +5,7 @@ from typing import List
 import sqlite3
 from pathlib import Path
 from typing import Optional
+import mysql.connector  
 
 app = FastAPI()
 # Allow requests from all origins
@@ -17,28 +18,36 @@ app.add_middleware(
 )
 
 
-# SQLite connection
-parent_directory = Path(__file__).resolve().parent.parent
-db_file_path = parent_directory / "my_ride.db"
-# print(db_file_path)
-conn = sqlite3.connect(db_file_path)
-
-cursor = conn.cursor()
-
-# Create the Reviews table if it doesn't exist
-cursor.execute('''
-    CREATE TABLE IF NOT EXISTS Reviews (
-        review_id INTEGER PRIMARY KEY AUTOINCREMENT,
-        user_id INT,
-        bike_id INT,
-        rating INT,
-        comment TEXT,
-        review_date DATETIME,
-        FOREIGN KEY (user_id) REFERENCES Users(user_id),
-        FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id)
-    )
-''')
-conn.commit()
+# # SQLite connection
+# parent_directory = Path(__file__).resolve().parent.parent
+# db_file_path = parent_directory / "my_ride.db"
+# # print(db_file_path)
+# conn = sqlite3.connect(db_file_path)
+# cursor = conn.cursor()
+
+# # Create the Reviews table if it doesn't exist
+# cursor.execute('''
+#     CREATE TABLE IF NOT EXISTS Reviews (
+#         review_id INTEGER PRIMARY KEY AUTOINCREMENT,
+#         user_id INT,
+#         bike_id INT,
+#         rating INT,
+#         comment TEXT,
+#         review_date DATETIME,
+#         FOREIGN KEY (user_id) REFERENCES Users(user_id),
+#         FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id)
+#     )
+# ''')
+# conn.commit()
+
+db_connection = mysql.connector.connect(
+    host='database_mysql',  # or '127.0.0.1' for IPv4 loopback
+    port='3306',  # Specify the port number here
+    user='root',
+    password='root_password',
+    database='your_database'
+)
+cursor = db_connection.cursor()
 
 
 # Review model
@@ -56,11 +65,11 @@ async def create_review(review: Review):
     cursor.execute('''
         INSERT INTO Reviews 
         (user_id, bike_id, rating, comment, review_date) 
-        VALUES (?, ?, ?, ?, ?)
+        VALUES (%s, %s, %s, %s, %s)
     ''', (
         review.user_id, review.bike_id, review.rating, review.comment, review.review_date
     ))
-    conn.commit()
+    db_connection.commit()
     return review
 
 
@@ -75,7 +84,7 @@ async def read_reviews():
             bike_id=review[1],
             rating=review[2],
             comment=review[3],
-            review_date=review[4]
+            review_date=review[4].strftime('%Y-%m-%d %H:%M:%S')
         )
         review_objects.append(review_obj)
     return review_objects
@@ -83,7 +92,7 @@ async def read_reviews():
 
 @app.get("/reviews/{review_id}", response_model=Review)
 async def read_review(review_id: int):
-    cursor.execute('SELECT * FROM Reviews WHERE review_id = ?', (review_id,))
+    cursor.execute('SELECT * FROM Reviews WHERE review_id = %s', (review_id,))
     review = cursor.fetchone()
     if review is None:
         raise HTTPException(status_code=404, detail="Review not found")
@@ -94,18 +103,18 @@ async def read_review(review_id: int):
 async def update_review(review_id: int, review: Review):
     cursor.execute('''
         UPDATE Reviews 
-        SET user_id = ?, bike_id = ?, rating = ?, comment = ?, review_date = ?
-        WHERE review_id = ?
+        SET user_id = %s, bike_id = %s, rating = %s, comment = %s, review_date = %s
+        WHERE review_id = %s
     ''', (
         review.user_id, review.bike_id, review.rating, review.comment,
         review.review_date, review_id
     ))
-    conn.commit()
+    db_connection.commit()
     return review
 
 
 @app.delete("/reviews/{review_id}")
 async def delete_review(review_id: int):
-    cursor.execute('DELETE FROM Reviews WHERE review_id = ?', (review_id,))
-    conn.commit()
+    cursor.execute('DELETE FROM Reviews WHERE review_id = %s', (review_id,))
+    db_connection.commit()
     return {"message": "Review deleted successfully"}
diff --git a/sql_files/common_insert.sql b/sql_files/common_insert.sql
new file mode 100644
index 0000000..dc084b5
--- /dev/null
+++ b/sql_files/common_insert.sql
@@ -0,0 +1,19 @@
+INSERT INTO Bikes (bike_id, model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history)
+VALUES
+(101, 'Mountain Bike', 'available', 'Central Park', 'good', 10.00, '2024-03-25', 'Cleaned and lubricated chain');
+
+INSERT INTO Users (user_id, username, password, email, phone_number, credit_card_info, registration_date, last_login)
+VALUES
+(1, 'john_doe', 'password123', 'john@example.com', '+1234567890', '**** **** **** 1234', '2024-03-28 10:00:00', '2024-03-28 10:00:00');
+
+INSERT INTO Rentals (rental_id, id, user_id, bike_id, year, hour, season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count)
+VALUES
+(1, 1001, 1, 101, 2024, 10, 1, 0, 1, 1, 15.5, 18.2, 67, 12.0, 3);
+
+INSERT INTO Reviews (review_id, user_id, bike_id, rating, comment, review_date)
+VALUES
+(1, 1, 101, 4, 'Great bike for off-road trails!', '2024-03-29 12:30:00');
+
+INSERT INTO Admins (admin_id, username, password, email, phone_number)
+VALUES
+(1, 'admin1', 'adminpass', 'admin1@example.com', '+1122334455');
diff --git a/sql_files/table_schema.sql b/sql_files/table_schema.sql
new file mode 100644
index 0000000..6be9952
--- /dev/null
+++ b/sql_files/table_schema.sql
@@ -0,0 +1,62 @@
+CREATE TABLE Users (
+    user_id INT PRIMARY KEY,
+    username VARCHAR(255),
+    password VARCHAR(255),
+    email VARCHAR(255),
+    phone_number VARCHAR(20),
+    credit_card_info VARCHAR(255),
+    registration_date DATETIME,
+    last_login DATETIME
+);
+
+CREATE TABLE Bikes (
+    bike_id INT PRIMARY KEY,
+    model VARCHAR(255),
+    bike_status VARCHAR(50),
+    current_location VARCHAR(255),
+    bike_condition VARCHAR(50),
+    price_per_hour DECIMAL(10, 2),
+    last_maintenance_date DATE,
+    maintenance_history TEXT
+);
+
+
+CREATE TABLE Rentals (
+    rental_id INT PRIMARY KEY,
+    id INT,
+    user_id INT,
+    bike_id INT,
+    year INT,
+    hour INT,
+    season INT,
+    holiday BOOLEAN,
+    workingday BOOLEAN,
+    weather INT,
+    temp DECIMAL(5, 2),
+    atemp DECIMAL(5, 2),
+    humidity DECIMAL(5, 2),
+    windspeed DECIMAL(5, 2),
+    count INT,
+    FOREIGN KEY (user_id) REFERENCES Users(user_id),
+    FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id)
+);
+
+CREATE TABLE Reviews (
+    review_id INT PRIMARY KEY,
+    user_id INT,
+    bike_id INT,
+    rating INT,
+    comment TEXT,
+    review_date DATETIME,
+    FOREIGN KEY (user_id) REFERENCES Users(user_id),
+    FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id)
+);
+
+CREATE TABLE Admins (
+    admin_id INT PRIMARY KEY,
+    username VARCHAR(255),
+    password VARCHAR(255),
+    email VARCHAR(255),
+    phone_number VARCHAR(20)
+);
+
diff --git a/users_service/main.py b/users_service/main.py
index 7d9f1f0..61852a9 100644
--- a/users_service/main.py
+++ b/users_service/main.py
@@ -3,6 +3,7 @@ from pydantic import BaseModel
 from fastapi.middleware.cors import CORSMiddleware
 from typing import List
 import sqlite3
+import mysql.connector   
 from pathlib import Path
 from typing import Optional
 
@@ -17,29 +18,37 @@ app.add_middleware(
     allow_headers=["*"],
 )
 
-# SQLite connection
-parent_directory = Path(__file__).resolve().parent.parent
-db_file_path = parent_directory / "my_ride.db"
-# print(db_file_path)
-conn = sqlite3.connect(db_file_path)
-
-cursor = conn.cursor()
-
-# Create the Users table if it doesn't exist
-cursor.execute('''
-    CREATE TABLE IF NOT EXISTS Users (
-        user_id INTEGER PRIMARY KEY,
-        username TEXT,
-        password TEXT,
-        email TEXT,
-        phone_number TEXT,
-        credit_card_info TEXT,
-        registration_date DATETIME,
-        last_login DATETIME
-    )
-''')
-conn.commit()
-
+# # SQLite connection
+# parent_directory = Path(__file__).resolve().parent.parent
+# db_file_path = parent_directory / "my_ride.db"
+# # print(db_file_path)
+# conn = sqlite3.connect(db_file_path)
+
+# cursor = conn.cursor()
+
+# # Create the Users table if it doesn't exist
+# cursor.execute('''
+#     CREATE TABLE IF NOT EXISTS Users (
+#         user_id INTEGER PRIMARY KEY,
+#         username TEXT,
+#         password TEXT,
+#         email TEXT,
+#         phone_number TEXT,
+#         credit_card_info TEXT,
+#         registration_date DATETIME,
+#         last_login DATETIME
+#     )
+# ''')
+# conn.commit()
+
+db_connection = mysql.connector.connect(
+    host='database_mysql',  # or '127.0.0.1' for IPv4 loopback
+    port='3306',  # Specify the port number here
+    user='root',
+    password='root_password',
+    database='your_database'
+)
+cursor = db_connection.cursor()
 
 class User(BaseModel):
     username: str
@@ -72,7 +81,7 @@ async def read_users():
             username=user[1],
             email=user[2],
             phone_number=user[3],
-            registration_date=user[4]
+            registration_date=user[4].strftime('%Y-%m-%d %H:%M:%S') 
         )
         user_objects.append(user_obj)
     return user_objects
@@ -87,7 +96,7 @@ async def create_user(user: User):
         cursor.execute('''
             INSERT INTO Users 
             (username, password, email, phone_number, registration_date) 
-            VALUES (?, ?, ?, ?, ?)
+            VALUES (%s, %s, %s, %s, %s)
         ''', (
             user.username, user.password, user.email, user.phone_number,
             user.registration_date
@@ -96,7 +105,7 @@ async def create_user(user: User):
         cursor.execute('''
             INSERT INTO Users 
             (username, password, email, phone_number, registration_date, last_login) 
-            VALUES (?, ?, ?, ?, ?, ?)
+            VALUES (%s, %s, %s, %s, %s)
         ''', (
             user.username, user.password, user.email, user.phone_number,
             user.registration_date, user.last_login
@@ -105,7 +114,7 @@ async def create_user(user: User):
         cursor.execute('''
             INSERT INTO Users 
             (username, password, email, phone_number, credit_card_info, registration_date) 
-            VALUES (?, ?, ?, ?, ?, ?)
+            VALUES (%s, %s, %s, %s, %s)
         ''', (
             user.username, user.password, user.email, user.phone_number,
             user.credit_card_info, user.registration_date
@@ -114,12 +123,12 @@ async def create_user(user: User):
         cursor.execute('''
             INSERT INTO Users 
             (username, password, email, phone_number, credit_card_info, registration_date, last_login) 
-            VALUES (?, ?, ?, ?, ?, ?, ?)
+            VALUES (%s, %s, %s, %s, %s)
         ''', (
             user.username, user.password, user.email, user.phone_number,
             user.credit_card_info, user.registration_date, user.last_login
         ))
-    conn.commit()
+    db_connection.commit()
     return user
 
 
@@ -137,19 +146,19 @@ async def read_user(user_id: int):
 async def update_user(user_id: int, user: User):
     cursor.execute('''
         UPDATE Users 
-        SET username = ?, password = ?, email = ?, phone_number = ?, 
-        credit_card_info = ?, registration_date = ?, last_login = ?
-        WHERE user_id = ?
+        SET username = %s, password = %s, email = %s, phone_number = %s, 
+        credit_card_info = %s, registration_date = %s, last_login = %s
+        WHERE user_id = %s
     ''', (
         user.username, user.password, user.email, user.phone_number,
         user.credit_card_info, user.registration_date, user.last_login, user_id
     ))
-    conn.commit()
+    db_connection.commit()
     return user
 
 
 @app.delete("/users/{user_id}")
 async def delete_user(user_id: int):
-    cursor.execute('DELETE FROM Users WHERE user_id = ?', (user_id,))
-    conn.commit()
+    cursor.execute('DELETE FROM Users WHERE user_id = %s', (user_id,))
+    db_connection.commit()
     return {"message": "User deleted successfully"}
-- 
GitLab