Skip to content

Commit

Permalink
Task 07
Browse files Browse the repository at this point in the history
  • Loading branch information
OluwaninsolaAO committed Apr 24, 2023
1 parent 8b7209f commit 369fe30
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 139 deletions.
109 changes: 53 additions & 56 deletions models/engine/db_storage.py
Original file line number Diff line number Diff line change
@@ -1,86 +1,83 @@
#!/usr/bin/python3
"""This module defines a class to manage db storage for hbnb clone"""
"""Defines a new engine that uses SQLAlchemy"""
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from ..base_model import Base, BaseModel
from os import getenv
from sqlalchemy import create_engine, inspect

HBNB_MYSQL_USER = getenv('HBNB_MYSQL_USER')
HBNB_MYSQL_PWD = getenv('HBNB_MYSQL_PWD')
HBNB_MYSQL_HOST = getenv('HBNB_MYSQL_HOST')
HBNB_MYSQL_DB = getenv('HBNB_MYSQL_DB')
HBNB_MYSQL_PORT = getenv('HBNB_MYSQL_PORT')
HBNB_ENV = 'dev'


class DBStorage:
"""This class manages storage of hbnb . in database"""
"""DBStorage Engine running on SQLAlchemy"""

__engine = None
__session = None

def __init__(self):
"""initializes the database"""
self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'
.format(HBNB_MYSQL_USER, HBNB_MYSQL_PWD,
HBNB_MYSQL_HOST, HBNB_MYSQL_DB),
pool_pre_ping=True)
if HBNB_ENV == 'test':
"""class constructor for DBStorage"""

credentials = ['HBNB_MYSQL_USER', 'HBNB_MYSQL_PWD',
'HBNB_MYSQL_HOST', 'HBNB_MYSQL_DB']
env = [os.environ.get(c) for c in credentials]
e = 'mysql+mysqldb://{}:{}@{}/{}'.format(*env[:])
self.__engine = create_engine(e, pool_pre_ping=True)
# Session = sessionmaker(bind=self.__engine)
# self.__session = Session()

# drop all tables if the environment variable
# HBNB_ENV is equal to test
if os.environ.get('HBNB_ENV') == 'test':
from models.base_model import Base
Base.metadata.drop_all(self.__engine)

def all(self, cls=None):
"""Returns a dictionary of all instances of a given class"""
from ..user import User
from ..state import State
from ..city import City
from ..place import Place
from ..review import Review
from ..amenity import Amenity
"""Queries the current database session (self.__session)
for all objects depending of the class name (argument cls)"""
from models.user import User
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.place import Place
from models.review import Review

result_dict = {}
for model in [User, State, City, Place, Amenity, Review]:
if cls is not None and model != cls:
continue
query_results = self.__session.query(model).all()
for obj in query_results:
key = "{}.{}".format(type(obj).__name__, obj.id)
result_dict[key] = obj
return result_dict
class_list = [State, City, User, Place, Review, Amenity]
objs = {}
if cls is not None:
for obj in self.__session.query(cls).all():
objs.update({obj.to_dict()['__class__'] + '.' + obj.id: obj})
else:
for class_item in class_list:
for obj in self.__session.query(class_item).all():
key = obj.to_dict()['__class__'] + '.' + obj.id
objs.update({key: obj})
return objs

def new(self, obj):
"""Adds new object to storage dictionary"""
if obj:
try:
self.__session.add(obj)
self.__session.flush()
self.__session.refresh(obj)
except Exception:
self.__session.rollback()
"""Add obj to the current database session"""
self.__session.add(obj)

def save(self):
"""Saves storage dictionary to file"""
"""Commit all changes of the current database session"""
self.__session.commit()

def delete(self, obj=None):
"""delete obj from __objects if it’s inside"""
"""Delete from the current database session obj if not None"""
if obj is not None:
self.__session.delete(obj)

def reload(self):
"""Loads storage dictionary from file"""
from ..user import User
from ..state import State
from ..city import City
from ..place import Place
from ..review import Review
from ..amenity import Amenity
"""Create all tables in the database
"""
from models.user import User
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.place import Place
from models.review import Review
from models.base_model import Base

Base.metadata.create_all(self.__engine)
session_factory = sessionmaker(
bind=self.__engine, expire_on_commit=False)
self.__session = scoped_session(session_factory)()
Session = sessionmaker(bind=self.__engine, expire_on_commit=False)
self.__session = scoped_session(Session)

def close(self):
"""calls remove() method on the private
session attribute (self.__session)"""
"""call close() method for commiting objects to db"""
self.__session.close()
83 changes: 0 additions & 83 deletions models/engine/db_storage.py.old

This file was deleted.

0 comments on commit 369fe30

Please sign in to comment.