Activity #20: Python Orm Sqlalchemy

Photo by Austin Chan on Unsplash

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.

python -m venv myvenv
myvenv\Scripts\activate

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 databaseORMQuizDb.py

named databaseORMQuizDb.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()

USER TALBE:

RESULT TABLE:

QUIZ TABLE:

QUESTION TABLE:

OPTION TABLE:

ANSWER TABLE:

2.Create a file named database ORMEcommerceDb.py

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Float, DateTime, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime, timezone

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    user_id = Column(Integer, primary_key=True)
    password = Column(String)
    name = Column(String)
    address = Column(String)
    phone = Column(String)
    role = Column(String)
    created_at = Column(DateTime, default=datetime.now(timezone.utc))

class Product(Base):
    __tablename__ = 'products'
    product_id = Column(Integer, primary_key=True)
    name = Column(String)
    brand = Column(String)
    description = Column(String)
    price = Column(Float)
    stock = Column(Integer)
    category = Column(String)
    sku = Column(String)
    image_url = Column(String)
    created_at = Column(DateTime, default=datetime.now(timezone.utc))

class Review(Base):
    __tablename__ = 'reviews'
    review_id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.user_id'))
    product_id = Column(Integer, ForeignKey('products.product_id'))
    rating = Column(Integer)
    comment = Column(Text)
    created_at = Column(DateTime, default=datetime.now(timezone.utc))

class OrderItem(Base):
    __tablename__ = 'order_items'
    order_item = Column(Integer, primary_key=True)
    order_id = Column(Integer)
    product_id = Column(Integer, ForeignKey('products.product_id'))
    quantity = Column(Integer)
    price = Column(Float)

class Order(Base):
    __tablename__ = 'orders'
    order_id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.user_id'))
    total_amount = Column(Float)
    status = Column(String)
    created_at = Column(DateTime, default=datetime.now(timezone.utc))

engine = create_engine('sqlite:///ORMEcommerceDb.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

session.add_all([
    User(password='pass1', name='Alice', address='123 Main St', phone='1234567890', role='customer'),
    User(password='pass2', name='Bob', address='456 Elm St', phone='0987654321', role='seller'),
    User(password='pass3', name='Charlie', address='789 Maple St', phone='5432167890', role='customer'),
    User(password='pass4', name='Diana', address='321 Oak St', phone='4567890123', role='admin'),
    User(password='pass5', name='Ethan', address='654 Pine St', phone='6789012345', role='customer'),

    Product(name='Laptop', brand='BrandA', description='Gaming Laptop', price=1200.00, stock=10,
            category='Electronics', sku='LAP123', image_url='https://example.com/laptop.jpg'),
    Product(name='Phone', brand='BrandB', description='Smartphone', price=700.00, stock=20,
            category='Electronics', sku='PHO456', image_url='https://example.com/phone.jpg'),
    Product(name='Tablet', brand='BrandC', description='Android Tablet', price=300.00, stock=15,
            category='Electronics', sku='TAB789', image_url='https://example.com/tablet.jpg'),
    Product(name='Headphones', brand='BrandD', description='Wireless Headphones', price=150.00, stock=25,
            category='Electronics', sku='HEA012', image_url='https://example.com/headphones.jpg'),
    Product(name='Smartwatch', brand='BrandE', description='Fitness Tracker', price=200.00, stock=30,
            category='Electronics', sku='SMA345', image_url='https://example.com/smartwatch.jpg'),

    Review(user_id=1, product_id=1, rating=5, comment='Excellent laptop!'),
    Review(user_id=2, product_id=2, rating=4, comment='Very good phone.'),
    Review(user_id=3, product_id=3, rating=3, comment='Average tablet.'),
    Review(user_id=4, product_id=4, rating=5, comment='Love these headphones!'),
    Review(user_id=5, product_id=5, rating=4, comment='Great smartwatch.'),

    OrderItem(order_id=1, product_id=1, quantity=1, price=1200.00),
    OrderItem(order_id=1, product_id=2, quantity=2, price=1400.00),
    OrderItem(order_id=2, product_id=3, quantity=1, price=300.00),
    OrderItem(order_id=2, product_id=4, quantity=3, price=450.00),
    OrderItem(order_id=3, product_id=5, quantity=1, price=200.00),

    Order(user_id=1, total_amount=2800.00, status='Completed'),
    Order(user_id=3, total_amount=300.00, status='Pending'),
    Order(user_id=2, total_amount=450.00, status='Shipped'),
    Order(user_id=4, total_amount=150.00, status='Delivered'),
    Order(user_id=5, total_amount=200.00, status='Cancelled'),
])

session.commit()
session.close()

USERS TABLE:

REVIEWS TABLE:

PRODUCTS TABLE:

ORDERS TABLE:

ORDER_ITEMS:

3. Create a file named database ORMJobBoardDb.py

from datetime import datetime, timezone
from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, Boolean, Enum, ForeignKey
from sqlalchemy.orm import declarative_base, sessionmaker

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'
    user_id = Column(Integer, primary_key=True)
    authentication_id = Column(Integer, ForeignKey('authentication.authentication_id'))
    name = Column(String)
    birthdate = Column(DateTime(timezone=True))
    skills = Column(Text)
    work_experience = Column(Text)
    updated_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))

class Authentication(Base):
    __tablename__ = 'authentication'
    authentication_id = Column(Integer, primary_key=True)
    username = Column(String)
    email = Column(String)
    password_hash = Column(String)
    role = Column(Enum('admin', 'employer', 'job_seeker'))
    stock = Column(Integer)
    created_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))
    updated_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))
    deleted_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))

class Message(Base):
    __tablename__ = 'message'
    message_id = Column(Integer, primary_key=True)
    sender_id = Column(Integer, ForeignKey('user.user_id'))
    recipient_id = Column(Integer, ForeignKey('user.user_id'))
    message = Column(Text)
    is_read = Column(Boolean)
    message_type = Column(Enum('TEXT', 'IMAGE', 'FILE'))
    send_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))
    deleted_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))

class Applications(Base):
    __tablename__ = 'applications'
    application_id = Column(Integer, primary_key=True)
    job_seeker_id = Column(Integer, ForeignKey('user.user_id'))
    job_id = Column(Integer, ForeignKey('job_posting.job_id'))
    resume = Column(Text)
    status = Column(Enum('PENDING', 'ACCEPTED', 'REJECTED'))
    skills = Column(Text)
    work_experience = Column(Text)
    applied_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))
    deleted_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))

class JobPosting(Base):
    __tablename__ = 'job_posting'
    job_id = Column(Integer, primary_key=True)
    employer_id = Column(Integer, ForeignKey('user.user_id'))
    job_title = Column(String)
    job_description = Column(Text)
    location = Column(String)
    category = Column(String)
    industry = Column(String)
    min_salary = Column(Integer)
    max_salary = Column(Integer)
    created_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))
    updated_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))
    deleted_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))

class JobInteraction(Base):
    __tablename__ = 'job_interaction'
    interaction_id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('user.user_id'))
    job_id = Column(Integer, ForeignKey('job_posting.job_id'))
    interaction_type = Column(Integer)
    interaction_date = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))
    is_applied = Column(Boolean)

engine = create_engine('sqlite:///ORMJobBoardDb.Db', connect_args={"check_same_thread": False})

# Ensure the database tables are created
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

# Adding data with correct datetime objects
session.add_all([
    User(user_id=1, authentication_id=1, name='Rimuru', birthdate=datetime(1990, 1, 1, tzinfo=timezone.utc),
         skills='Python, SQL', work_experience='5 years'),
    User(user_id=2, authentication_id=2, name='Diablo', birthdate=datetime(1988, 2, 1, tzinfo=timezone.utc),
         skills='Java, NoSQL', work_experience='7 years'),
    User(user_id=3, authentication_id=3, name='Testarossa', birthdate=datetime(1992, 3, 1, tzinfo=timezone.utc),
         skills='JavaScript, React', work_experience='4 years'),
    User(user_id=4, authentication_id=4, name='Carrera', birthdate=datetime(1985, 4, 1, tzinfo=timezone.utc),
         skills='HTML, CSS', work_experience='6 years'),
    User(user_id=5, authentication_id=5, name='Ultima', birthdate=datetime(1975, 5, 1, tzinfo=timezone.utc),
         skills='C++, C#', work_experience='10 years'),

    Authentication(authentication_id=1, username='Rimuru', email='rimuru@gmail.com', password_hash='hashedpw1',
                   role='job_seeker', stock=0),
    Authentication(authentication_id=2, username='Diablo', email='diablo@gmail.com', password_hash='hashedpw2',
                   role='employer', stock=0),
    Authentication(authentication_id=3, username='Testarrosa', email='testarrosa@gmail.com', password_hash='hashedpw3',
                   role='job_seeker', stock=0),
    Authentication(authentication_id=4, username='Carrera', email='carrera@gmail.com', password_hash='hashedpw4',
                   role='employer', stock=0),
    Authentication(authentication_id=5, username='Ultima', email='ultima@gmail.com', password_hash='hashedpw5',
                   role='job_seeker', stock=0),

    Message(message_id=1, sender_id=1, recipient_id=2, message='Hello!', is_read=False, message_type='TEXT'),
    Message(message_id=2, sender_id=2, recipient_id=3, message='Job opportunity for you!', is_read=False,
            message_type='TEXT'),
    Message(message_id=3, sender_id=3, recipient_id=4, message='Interested in the job!', is_read=True,
            message_type='TEXT'),
    Message(message_id=4, sender_id=4, recipient_id=5, message='Please send your resume.', is_read=False,
            message_type='TEXT'),
    Message(message_id=5, sender_id=5, recipient_id=1, message='Can we schedule an interview?', is_read=False,
            message_type='TEXT'),

    Applications(application_id=1, job_seeker_id=1, job_id=1, resume='Rimuru_Resume.pdf', status='PENDING',
                 skills='Python', work_experience='5 years'),
    Applications(application_id=2, job_seeker_id=2, job_id=2, resume='Diablo_Resume.pdf', status='ACCEPTED',
                 skills='Java', work_experience='7 years'),
    Applications(application_id=3, job_seeker_id=3, job_id=3, resume='Testarrosa_Resume.pdf', status='REJECTED',
                 skills='JavaScript', work_experience='4 years'),
    Applications(application_id=4, job_seeker_id=4, job_id=4, resume='Carrera_Resume.pdf', status='PENDING',
                 skills='HTML', work_experience='6 years'),
    Applications(application_id=5, job_seeker_id=5, job_id=5, resume='Ultima_Resume.pdf', status='ACCEPTED',
                 skills='C++', work_experience='10 years'),

    JobPosting(job_id=1, employer_id=2, job_title='Python Developer',
               job_description='Develop applications using Python.', location='New York', category='IT',
               industry='Software', min_salary=70000, max_salary=100000),
    JobPosting(job_id=2, employer_id=4, job_title='Java Developer', job_description='Develop applications using Java.',
               location='San Francisco', category='IT', industry='Software', min_salary=80000, max_salary=120000),
    JobPosting(job_id=3, employer_id=2, job_title='Frontend Developer',
               job_description='Work on the UI of the application.', location='Austin', category='IT',
               industry='Software', min_salary=60000, max_salary=90000),
    JobPosting(job_id=4, employer_id=4, job_title='Full Stack Developer',
               job_description='Work on both frontend and backend.', location='Seattle', category='IT',
               industry='Software', min_salary=90000, max_salary=130000),
    JobPosting(job_id=5, employer_id=2, job_title='Data Scientist', job_description='Analyze data and create reports.',
               location='Chicago', category='IT', industry='Software', min_salary=80000, max_salary=110000),

    JobInteraction(interaction_id=1, user_id=1, job_id=1, interaction_type=1, interaction_date=datetime.now(timezone.utc),
                   is_applied=True),
    JobInteraction(interaction_id=2, user_id=2, job_id=2, interaction_type=1, interaction_date=datetime.now(timezone.utc),
                   is_applied=False),
    JobInteraction(interaction_id=3, user_id=3, job_id=3, interaction_type=1, interaction_date=datetime.now(timezone.utc),
                   is_applied=True),
    JobInteraction(interaction_id=4, user_id=4, job_id=4, interaction_type=1, interaction_date=datetime.now(timezone.utc),
                   is_applied=True),
    JobInteraction(interaction_id=5, user_id=5, job_id=5, interaction_type=1, interaction_date=datetime.now(timezone.utc),
                   is_applied=False)
])

session.commit()
session.close()

USER TABLE:

MESSAGE TABLE:

JOB_POSTING:

JOB_INTERACTION:

AUTHENTICATION:

APPLICATIONS:

4. Create a file named database ORMEventManagementDb.py

from sqlalchemy import create_engine, Column, Integer, String, Text, Date, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime

DATABASE_URI = 'sqlite:///ORMEventManagementDb.db'
engine = create_engine(DATABASE_URI)
Base = declarative_base()

class Admin(Base):
    __tablename__ = 'admin'
    admin_id = Column(Integer, primary_key=True)
    admin_username = Column(String)
    admin_email = Column(String)
    admin_password = Column(String)

class User(Base):
    __tablename__ = 'user'
    user_id = Column(Integer, primary_key=True)
    user_gmail = Column(String)
    user_password = Column(String)
    user_lastname = Column(String)

class Events(Base):
    __tablename__ = 'events'
    event_id = Column(Integer, primary_key=True)
    event_title = Column(String)
    event_description = Column(String)
    event_additional_description = Column(Text)
    event_address = Column(String)
    event_planner = Column(String)
    event_image = Column(String)
    event_status = Column(String)
    event_start = Column(Date)

class Agenda(Base):
    __tablename__ = 'agenda'
    agenda_id = Column(Integer, primary_key=True)
    event_id = Column(Integer, ForeignKey('events.event_id'))
    agenda_time_start = Column(String)
    agenda_time_end = Column(String)

class Attendees(Base):
    __tablename__ = 'attendees'
    attendees_id = Column(Integer, primary_key=True)
    invitation_id = Column(Integer, ForeignKey('invited.invitation_id'))

class Invited(Base):
    __tablename__ = 'invited'
    invitation_id = Column(Integer, primary_key=True)
    invitation_name = Column(String)
    event_id = Column(Integer, ForeignKey('events.event_id'))
    attendee_type = Column(String)
    seat_number = Column(String)

Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

admin_data = [
    Admin(admin_id=1, admin_username='admin1', admin_email='admin1@gmail.com', admin_password='adminpass1'),
    Admin(admin_id=2, admin_username='admin2', admin_email='admin2@gmail.com', admin_password='adminpass2'),
    Admin(admin_id=3, admin_username='admin3', admin_email='admin3@gmail.com', admin_password='adminpass3'),
    Admin(admin_id=4, admin_username='admin4', admin_email='admin4@gmail.com', admin_password='adminpass4'),
    Admin(admin_id=5, admin_username='admin5', admin_email='admin5@gmail.com', admin_password='adminpass5'),
]

user_data = [
    User(user_id=1, user_gmail='Rimuru@gmail.com', user_password='password1', user_lastname='Tempest'),
    User(user_id=2, user_gmail='Diablo@gmail.com', user_password='password2', user_lastname='Noir'),
    User(user_id=3, user_gmail='Testarrosa@gmail.com', user_password='password3', user_lastname='Blanc'),
    User(user_id=4, user_gmail='Carrera@gmail.com', user_password='password4', user_lastname='Jaune'),
    User(user_id=5, user_gmail='Ultima@gmail.com', user_password='password5', user_lastname='Violet'),
]

event_data = [
    Events(event_id=1, event_title='Harvest Festival 2023', event_description='Celebrate the bountiful harvest with food, fun, and family activities!', event_additional_description='Join us for an unforgettable day filled with local produce, craft vendors, live music, and childrens activities', event_address='123 Farm Lane, Springfield, IL 62701', event_planner='Planner One', event_image='image1.jpg', event_status='active', event_start=datetime.strptime('2023-11-01', '%Y-%m-%d').date()),
    Events(event_id=2, event_title='Tech Innovation Summit', event_description='Explore the latest trends in technology and entrepreneurship.', event_additional_description='This summit gathers industry leaders, startups, and innovators to discuss the future of technology.', event_address='456 Tech Ave, Silicon Valley, CA 94043', event_planner='Planner Two', event_image='image2.jpg', event_status='active', event_start=datetime.strptime('2023-11-02', '%Y-%m-%d').date()),
    Events(event_id=3, event_title='Art in the Park', event_description='An outdoor art exhibition featuring local artists.', event_additional_description='Come and enjoy a day of creativity and inspiration at our annual Art in the Park! Browse art installations, enjoy live music, and meet local artists.', event_address='City Park, 789 Art St, Denver, CO 80204', event_planner='Planner Three', event_image='image3.jpg', event_status='active', event_start=datetime.strptime('2023-11-03', '%Y-%m-%d').date()),
    Events(event_id=4, event_title='Mindfulness Meditation Retreat', event_description='A weekend retreat to relax and rejuvenate your mind and body.', event_additional_description='Escape the hustle and bustle of daily life at our Mindfulness Meditation Retreat.', event_address='Serenity Hills Lodge, 234 Tranquil Rd, Asheville, NC 28801', event_planner='Planner Four', event_image='image4.jpg', event_status='active', event_start=datetime.strptime('2023-11-04', '%Y-%m-%d').date()),
    Events(event_id=5, event_title='Music Under the Stars', event_description='A night of live music and community spirit under the stars.', event_additional_description='Gather your friends and family for an evening of live performances from local bands.', event_address='Starry Park, 345 Rhythm Ln, Nashville, TN 37201', event_planner='Planner Five', event_image='image5.jpg', event_status='active', event_start=datetime.strptime('2023-11-05', '%Y-%m-%d').date()),
]

agenda_data = [
    Agenda(agenda_id=1, event_id=1, agenda_time_start='10:00', agenda_time_end='11:00'),
    Agenda(agenda_id=2, event_id=2, agenda_time_start='11:00', agenda_time_end='12:00'),
    Agenda(agenda_id=3, event_id=3, agenda_time_start='12:00', agenda_time_end='13:00'),
    Agenda(agenda_id=4, event_id=4, agenda_time_start='13:00', agenda_time_end='14:00'),
    Agenda(agenda_id=5, event_id=5, agenda_time_start='14:00', agenda_time_end='15:00'),
]

attendee_data = [
    Attendees(attendees_id=1, invitation_id=1),
    Attendees(attendees_id=2, invitation_id=2),
    Attendees(attendees_id=3, invitation_id=3),
    Attendees(attendees_id=4, invitation_id=4),
    Attendees(attendees_id=5, invitation_id=5),
]

invited_data = [
    Invited(invitation_id=1, invitation_name='Rimuru', event_id=1, attendee_type='VIP', seat_number='A1'),
    Invited(invitation_id=2, invitation_name='Diablo', event_id=2, attendee_type='Regular', seat_number='B1'),
    Invited(invitation_id=3, invitation_name='Testarrosa', event_id=3, attendee_type='VIP', seat_number='C1'),
    Invited(invitation_id=4, invitation_name='Carrera', event_id=4, attendee_type='Regular', seat_number='D1'),
    Invited(invitation_id=5, invitation_name='Ultima', event_id=5, attendee_type='VIP', seat_number='E1'),
]

session.add_all(admin_data)
session.add_all(user_data)
session.add_all(event_data)
session.add_all(agenda_data)
session.add_all(attendee_data)
session.add_all(invited_data)

session.commit()
session.close()

USER TABLE:

INVITED TABLE:

EVENTS TABLE:

ATTENDEES TABLE:

AGENDA TABLE:

ADMIN TABLE:

5. Create a file named database ORMTravelBookingDb.py

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='rimuru1', password_hash='hashed_password1', email='rimuru@gmail.com', phone_number='09933214290', first_name='rimuru', last_name='Tempest', user_role='ADMIN'),
    User(username='diablo2', password_hash='hashed_password2', email='diablo@gmail.com', phone_number='09933214291', first_name='diablo', last_name='Noir', user_role='USERS'),
    User(username='testarrosa3', password_hash='hashed_password3', email='testarrosa@gmail.com', phone_number='09933214292', first_name='testarrosa', last_name='Blanc', user_role='ADMIN'),
    User(username='carrera4', password_hash='hashed_password4', email='carrera@gmail.com', phone_number='09933214293', first_name='carrera', last_name='Jaune', user_role='USERS'),
    User(username='ultima5', password_hash='hashed_password5', email='ultima@gmail.com', phone_number='09933214294', first_name='ultima', last_name='Violet', 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()

USERS TABLE:

TOURS TABLE:

REVIEWS TABLE:

PAYMENTS TABLE:

BOOKINGS TABLE:

ADMIN_LOGS TABLE:

RomelUsigan/Usigan_Python_Orm_Sqlalchemy