def create_book(self, name, price, author): """ Validates name & price & author type Validates Book is not exists by name Creates a new book into the BOOKS's table :param name: str :param price: int | float :param author: Author :return: Book | None """ # Validates name if not TypeUtils.is_type(name, var_type=str): print(ErrorMsgUtils.type_error(name, var_type=str)) return # Validates price if not TypeUtils.is_type_or(price, var_type1=int, var_type2=float): print(ErrorMsgUtils.none_of_type(int, float, var=print())) return # Validates author if not TypeUtils.is_type(author, var_type=Author): print(ErrorMsgUtils.type_error(author, var_type=Author)) return # Validates existence book_to_check = self.find_by_name(name) if book_to_check is not None: print(ErrorMsgUtils.already_exists(name)) return # Validates author existence author_db = AuthorDBDAO(db=self.db) author_by_id = author_db.find_by_id(author.id) if author_by_id is None: print( ErrorMsgUtils.does_not_exists(table_name='Author', var=author.id)) return # SQL & Execution sql = f"INSERT INTO BOOKS (NAME, PRICE, AUTHOR_ID) VALUES ('{name}', {price}, {author.id})" try: self.cursor.execute(sql) self.db.commit() except mysql.connector.Error as error: print(ErrorMsgUtils.display_error(error)) # Return None return None else: print(self.cursor.rowcount, "was inserted.") print("ID: ", self.cursor.lastrowid) # Return the Book return Book(name=name, price=price, id=self.cursor.lastrowid, author_id=author.id)
def price(self, new_price): # Validates type if not TypeUtils.is_type_or(new_price, var_type1=int, var_type2=float): print(ErrorMsgUtils.none_of_type(int, float, var=new_price)) return # Validates legal value if new_price <= 0: print(ErrorMsgUtils.illegal_value(new_price)) return # Set value self.__price = new_price