Activity 20: Python Orm Sqlalchemy
Step 1: Set Up the Environment
Install Python
Make sure you have Python installed or Any application like Vs code, Pycharm Etc.
Step 2: Install SQLAlchemy
Install SQLAlchemy using pip in your terminal.
pip install sqlalchemy
Step 3: Create the Database Setup
1.Create a file named database
ORMQuizDb.py
named database
ORMQuizDb.py
from sqlalchemy import create_engine, Column, Integer, String, Text, Enum, DateTime, Boolean, ForeignKey, DECIMAL
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime, timezone
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
user_id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
email = Column(String, nullable=False)
password = Column(String, nullable=False)
role = Column(Enum('teacher', 'student', name='user_roles'), nullable=False)
createdAt = Column(DateTime, default=datetime.now(timezone.utc))
updatedAt = Column(DateTime, default=datetime.now(timezone.utc), onupdate=datetime.now(timezone.utc))
class Quiz(Base):
__tablename__ = 'quiz'
quiz_id = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
description = Column(Text)
quiz_code = Column(String, unique=True)
teacher_id = Column(Integer, ForeignKey('user.user_id'))
duration = Column(Integer)
createdAt = Column(DateTime, default=datetime.now(timezone.utc))
updatedAt = Column(DateTime, default=datetime.now(timezone.utc), onupdate=datetime.now(timezone.utc))
teacher = relationship("User")
class Question(Base):
__tablename__ = 'question'
question_id = Column(Integer, primary_key=True)
quiz_id = Column(Integer, ForeignKey('quiz.quiz_id'))
question_text = Column(Text, nullable=False)
question_type = Column(Enum('MCQ', 'true or false', 'short answer', 'multimedia', name='question_types'))
createdAt = Column(DateTime, default=datetime.now(timezone.utc))
updatedAt = Column(DateTime, default=datetime.now(timezone.utc), onupdate=datetime.now(timezone.utc))
class Option(Base):
__tablename__ = 'option'
option_id = Column(Integer, primary_key=True)
question_id = Column(Integer, ForeignKey('question.question_id'))
option_text = Column(String, nullable=False)
is_correct = Column(Boolean)
class Answer(Base):
__tablename__ = 'answer'
answer_id = Column(Integer, primary_key=True)
question_id = Column(Integer, ForeignKey('question.question_id'))
student_id = Column(Integer, ForeignKey('user.user_id'))
answer_text = Column(Text)
submitted_At = Column(DateTime, default=datetime.now(timezone.utc))
class Result(Base):
__tablename__ = 'result'
result_id = Column(Integer, primary_key=True)
quiz_id = Column(Integer, ForeignKey('quiz.quiz_id'))
student_id = Column(Integer, ForeignKey('user.user_id'))
score = Column(DECIMAL(5, 2))
submitted_At = Column(DateTime, default=datetime.now(timezone.utc))
engine = create_engine('sqlite:///ORMQuizDb.sqlite')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
def add_dummy_data():
users = [
User(name='Alice', email='alice@example.com', password='password', role='student'),
User(name='Bob', email='bob@example.com', password='password', role='teacher'),
User(name='Charlie', email='charlie@example.com', password='password', role='student'),
User(name='David', email='david@example.com', password='password', role='teacher'),
User(name='Eve', email='eve@example.com', password='password', role='student')
]
session.add_all(users)
session.commit()
quizzes = [
Quiz(title='Math Quiz 1', description='Basic Math Quiz', quiz_code='MATH101', teacher_id=2, duration=30),
Quiz(title='Science Quiz 1', description='Basic Science Quiz', quiz_code='SCI101', teacher_id=4, duration=30),
Quiz(title='History Quiz 1', description='World History Quiz', quiz_code='HIST101', teacher_id=2, duration=30),
Quiz(title='Geography Quiz 1', description='Geography Basics Quiz', quiz_code='GEOG101', teacher_id=4, duration=30),
Quiz(title='Literature Quiz 1', description='Basic Literature Quiz', quiz_code='LIT101', teacher_id=2, duration=30),
]
session.add_all(quizzes)
session.commit()
questions = [
Question(quiz_id=1, question_text='What is 2 + 2?', question_type='MCQ'),
Question(quiz_id=1, question_text='Is the Earth flat?', question_type='true or false'),
Question(quiz_id=2, question_text='What is H2O commonly known as?', question_type='short answer'),
Question(quiz_id=2, question_text='What is the capital of France?', question_type='MCQ'),
Question(quiz_id=3, question_text='Who was the first President of the USA?', question_type='short answer'),
]
session.add_all(questions)
session.commit()
options = [
Option(question_id=1, option_text='3', is_correct=False),
Option(question_id=1, option_text='4', is_correct=True),
Option(question_id=1, option_text='5', is_correct=False),
Option(question_id=2, option_text='True', is_correct=False),
Option(question_id=2, option_text='False', is_correct=True),
Option(question_id=4, option_text='London', is_correct=False),
Option(question_id=4, option_text='Paris', is_correct=True),
Option(question_id=4, option_text='Berlin', is_correct=False),
Option(question_id=5, option_text='George Washington', is_correct=True),
Option(question_id=5, option_text='Abraham Lincoln', is_correct=False),
]
session.add_all(options)
session.commit()
answers = [
Answer(question_id=1, student_id=1, answer_text='4'),
Answer(question_id=2, student_id=3, answer_text='False'),
Answer(question_id=3, student_id=1, answer_text='Water'),
Answer(question_id=4, student_id=1, answer_text='Paris'),
Answer(question_id=5, student_id=3, answer_text='George Washington')
]
session.add_all(answers)
session.commit()
results = [
Result(quiz_id=1, student_id=1, score=80.00),
Result(quiz_id=2, student_id=3, score=90.00),
Result(quiz_id=3, student_id=1, score=85.00),
Result(quiz_id=4, student_id=2, score=75.00),
Result(quiz_id=5, student_id=3, score=95.00)
]
session.add_all(results)
session.commit()
add_dummy_data()
def crud_example():
print("All Users:")
for user in session.query(User).all():
print(user.name, user.email)
user_to_update = session.query(User).filter_by(user_id=1).first()
user_to_update.name = 'Alicia'
session.commit()
user_to_delete = session.query(User).filter_by(user_id=3).first()
session.delete(user_to_delete)
session.commit()
print("\nUsers after update and delete:")
for user in session.query(User).all():
print(user.name, user.email)
crud_example()
session.close()
The a database management tool, likely a database browser or IDE, connected to a SQLite database file named "ORMQuizDb.db". The database appears to be relatively small, with a size of 32 kilobytes.
The database contains six tables: "answer", "option", "question", "quiz", "result", and "user". These table names suggest that the database is used for storing and managing quiz-related data, including questions, answers, options, quizzes, results, and user information.
The presence of a "Views" section indicates that the database might also include virtual tables or views, which can be used to simplify complex queries or present data in a specific way.
The displays the structure of a database named ORMEcommerceDb.db
, which appears to be designed for an e-commerce system. It includes five tables: order_items
, orders
, products
, reviews
, and users
.
The order_items
table contains columns for order_item
, order_id
, product_id
, quantity
, and price
, suggesting it handles the details of individual products within orders. The orders
table likely tracks customer orders, while the products
table manages product details. reviews
may store customer feedback on products, and users
likely contains customer or user account information. This schema supports core functionalities of an e-commerce platform, including orders, product management, and user interaction.
The depicts a database named ORMEventManagementDb.db
, containing six tables: admin
, agenda
, attendees
, events
, invited
, and user
. This schema likely supports an event management system. It organizes event details (events
), schedules (agenda
), participants (attendees
), invitees (invited
), administrators (admin
), and general users (user
).
The showcases the structure of a database named ORMJobBoardDb.Db
, likely visualized using an IDE like Visual Studio Code. It contains six tables: applications
, authentication
, job_interaction
, job_posting
, message
, and user
. These tables suggest that the database is part of a job board or recruitment system. The user
table likely stores user profiles, while authentication
manages login credentials. job_posting
holds details about available jobs, and applications
tracks user submissions for these jobs. job_interaction
may record activities like job views or clicks, and message
facilitates communication between users. This schema highlights key functionalities of a modern job board platform.
the database structure for ORMTravelBookingDb
in a SQL editor, featuring six tables: admin_logs
, bookings
, payments
, reviews
, tours
, and users
. Each table plays a specific role in managing the travel booking system. The admin_logs
table tracks administrative activities for security and monitoring. The bookings
table records travel reservations made by users. The payments
table handles transaction details associated with bookings. The reviews
table collects user feedback on tours or services. The tours
table contains information about available travel packages, including destinations and prices. Lastly, the users
table stores user details, facilitating user account management.
from sqlalchemy import create_engine, Column, Integer, String, Text, Date, Enum, DECIMAL, DateTime, ForeignKey
from sqlalchemy.orm import declarative_base, sessionmaker
import datetime
from datetime import timezone
DATABASE_URI = 'sqlite:///ORMTravelBookingDb.db'
engine = create_engine(DATABASE_URI, echo=False)
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
user_id = Column(Integer, primary_key=True)
username = Column(String(255), unique=True)
password_hash = Column(String(255))
email = Column(String(100), unique=True)
phone_number = Column(String(20))
first_name = Column(String(50))
last_name = Column(String(50))
user_role = Column(Enum('ADMIN', 'USERS'))
created_at = Column(DateTime, default=datetime.datetime.now(timezone.utc))
updated_at = Column(DateTime, default=datetime.datetime.now(timezone.utc), onupdate=datetime.datetime.now(timezone.utc))
deleted_at = Column(DateTime, default=datetime.datetime.now(timezone.utc))
class Tour(Base):
__tablename__ = 'tours'
tour_id = Column(Integer, primary_key=True)
tour_name = Column(String)
description = Column(Text)
price = Column(DECIMAL(10, 2))
start_date = Column(Date)
end_date = Column(Date)
seats_available = Column(Integer)
image_url = Column(String(255))
created_at = Column(DateTime, default=datetime.datetime.now(timezone.utc))
updated_at = Column(DateTime, default=datetime.datetime.now(timezone.utc), onupdate=datetime.datetime.now(timezone.utc))
deleted_at = Column(DateTime, default=datetime.datetime.now(timezone.utc))
class Payment(Base):
__tablename__ = 'payments'
payment_id = Column(Integer, primary_key=True)
booking_id = Column(Integer, ForeignKey('bookings.booking_id'), nullable=False)
payment_date = Column(DateTime, default=datetime.datetime.now(timezone.utc))
amount = Column(DECIMAL(10, 2))
payment_method = Column(Enum('GCASH'))
payment_status = Column(Enum('SUCCESS', 'FAILED'))
transaction_id = Column(String(100))
class Booking(Base):
__tablename__ = 'bookings'
booking_id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.user_id'), nullable=False)
tour_id = Column(Integer, ForeignKey('tours.tour_id'), nullable=False)
booking_date = Column(DateTime, default=datetime.datetime.now(timezone.utc))
travel_date = Column(Date)
seats_booked = Column(Integer)
total_amount = Column(DECIMAL(10, 2))
payment_status = Column(Enum('SUCCESS', 'FAILED'))
created_at = Column(DateTime, default=datetime.datetime.now(timezone.utc))
updated_at = Column(DateTime, default=datetime.datetime.now(timezone.utc), onupdate=datetime.datetime.now(timezone.utc))
class Review(Base):
__tablename__ = 'reviews'
review_id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.user_id'), nullable=False)
tour_id = Column(Integer, ForeignKey('tours.tour_id'), nullable=False)
rating = Column(Integer)
comment = Column(Text)
created_at = Column(DateTime, default=datetime.datetime.now(timezone.utc))
class AdminLog(Base):
__tablename__ = 'admin_logs'
log_id = Column(Integer, primary_key=True)
admin_id = Column(Integer, ForeignKey('users.user_id'), nullable=False)
action_type = Column(Enum('CREATE', 'UPDATE', 'DELETE'))
description = Column(Text)
timestamp = Column(DateTime, default=datetime.datetime.now(timezone.utc))
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
user_data = [
User(username='xavier14', password_hash='hashed_password1', email='xavier@gmail.com', phone_number='09933214290', first_name='Xavier', last_name='Avelino', user_role='ADMIN'),
User(username='fierci26', password_hash='hashed_password2', email='fierci@gmail.com', phone_number='09933214291', first_name='Fercival', last_name='Adawe', user_role='USERS'),
User(username='roerenz69', password_hash='hashed_password3', email='roerenz@gmail.com', phone_number='09933214292', first_name='Roerenz', last_name='Cano', user_role='ADMIN'),
User(username='rodney04', password_hash='hashed_password4', email='rodney@gmail.com', phone_number='09933214293', first_name='Rodney', last_name='Idanan', user_role='USERS'),
User(username='james12', password_hash='hashed_password5', email='james@gmail.com', phone_number='09933214294', first_name='James', last_name='Taay', user_role='USERS')
]
session.add_all(user_data)
session.commit()
tour_data = [
Tour(tour_name='City Tour', description='Explore the city attractions.', price=50.00, start_date=datetime.date(2023, 12, 1), end_date=datetime.date(2023, 12, 31), seats_available=10, image_url='image1.jpg'),
Tour(tour_name='Mountain Trek', description='Hike through the mountains.', price=75.00, start_date=datetime.date(2023, 11, 1), end_date=datetime.date(2023, 11, 15), seats_available=5, image_url='image2.jpg'),
Tour(tour_name='Beach Getaway', description='Relax at the sunny beach.', price=100.00, start_date=datetime.date(2023, 11, 10), end_date=datetime.date(2023, 11, 20), seats_available=20, image_url='image3.jpg'),
Tour(tour_name='Historical Sites', description='Visit ancient historical sites.', price=60.00, start_date=datetime.date(2023, 12, 5), end_date=datetime.date(2023, 12, 25), seats_available=15, image_url='image4.jpg'),
Tour(tour_name='Wildlife Safari', description='Experience wildlife up close.', price=120.00, start_date=datetime.date(2023, 12, 10), end_date=datetime.date(2023, 12, 20), seats_available=8, image_url='image5.jpg')
]
session.add_all(tour_data)
session.commit()
booking_data = [
Booking(user_id=1, tour_id=1, travel_date=datetime.date(2023, 12, 15), seats_booked=2, total_amount=100.00, payment_status='SUCCESS'),
Booking(user_id=2, tour_id=2, travel_date=datetime.date(2023, 11, 10), seats_booked=1, total_amount=75.00, payment_status='SUCCESS'),
Booking(user_id=3, tour_id=3, travel_date=datetime.date(2023, 11, 20), seats_booked=3, total_amount=300.00, payment_status='FAILED'),
Booking(user_id=4, tour_id=4, travel_date=datetime.date(2023, 12, 10), seats_booked=4, total_amount=240.00, payment_status='SUCCESS'),
Booking(user_id=5, tour_id=5, travel_date=datetime.date(2023, 12, 12), seats_booked=2, total_amount=240.00, payment_status='SUCCESS')
]
session.add_all(booking_data)
session.commit()
payment_data = [
Payment(booking_id=1, amount=100.00, payment_method='GCASH', payment_status='SUCCESS', transaction_id='TRANS001'),
Payment(booking_id=2, amount=75.00, payment_method='GCASH', payment_status='SUCCESS', transaction_id='TRANS002'),
# Adjust booking_id to match those added above, and ensure they exist.
Payment(booking_id=3, amount=300.00, payment_method='GCASH', payment_status='FAILED', transaction_id='TRANS003'),
Payment(booking_id=4, amount=240.00, payment_method='GCASH', payment_status='SUCCESS', transaction_id='TRANS004'),
Payment(booking_id=5, amount=240.00, payment_method='GCASH', payment_status='SUCCESS', transaction_id='TRANS005')
]
session.add_all(payment_data)
session.commit()
review_data = [
Review(user_id=1, tour_id=1, rating=5, comment='Great tour!'),
Review(user_id=2, tour_id=2, rating=4, comment='Enjoyed the trek!'),
Review(user_id=3, tour_id=3, rating=3, comment='It was okay.'),
Review(user_id=4, tour_id=4, rating=5, comment='Loved the history!'),
Review(user_id=5, tour_id=5, rating=5, comment='Amazing experience!')
]
session.add_all(review_data)
session.commit()
admin_log_data = [
AdminLog(admin_id=3, action_type='CREATE', description='Created a new tour.'),
AdminLog(admin_id=3, action_type='UPDATE', description='Updated tour prices.'),
AdminLog(admin_id=3, action_type='DELETE', description='Deleted a tour.'),
AdminLog(admin_id=3, action_type='CREATE', description='Created a new booking.'),
AdminLog(admin_id=3, action_type='CREATE', description='Created a new user.')
]
session.add_all(admin_log_data)
session.commit()
session.close()