def find_by_name(self, first_name, last_name): """ Validates first_name & last_name are str Returns Author if exists :param first_name: str :param last_name: str :return: Author | None """ # Validates type if not TypeUtils.all_of_type(first_name, last_name, var_type=str): print(ErrorMsgUtils.type_error(first_name, last_name, var_type=str)) return # Validate legal value if not first_name: print(ErrorMsgUtils.illegal_value(first_name)) if not last_name: print(ErrorMsgUtils.illegal_value(last_name)) sql = f"SELECT * FROM AUTHOR WHERE FIRST_NAME = '{first_name}' AND LAST_NAME = '{last_name}'" # Execution try: self.cursor.execute(sql) results = self.cursor.fetchone() if not results: print( ErrorMsgUtils.does_not_exists( table_name='Author', var=f"{first_name}, {last_name}")) return # Return results return Author(id=results[0], first_name=results[1], last_name=results[2]) except mysql.connector.Error as error: print(ErrorMsgUtils.display_error(error))
def create_author(self, first_name, last_name): """ Validates type first_name & last_name is str Validates author does not exists by first & last name :param first_name: str :param last_name: str :return: Author | None """ # Validates type if not TypeUtils.all_of_type(first_name, last_name, var_type=str): print(ErrorMsgUtils.type_error(first_name, last_name, var_type=str)) return # Validate existence author_to_check = self.find_by_name(first_name, last_name) if author_to_check is not None: print(ErrorMsgUtils.already_exists(f"{first_name}-{last_name}")) return sql = f"INSERT INTO AUTHOR(FIRST_NAME, LAST_NAME) VALUES ('{first_name}', '{last_name}')" # Execution try: self.cursor.execute(sql) self.db.commit() # Error except mysql.connector.Error as error: print(ErrorMsgUtils.display_error(error)) else: print(self.cursor.rowcount, "was inserted.") print("ID: ", self.cursor.lastrowid) # Return the Book return Author(first_name=first_name, last_name=last_name, id=self.cursor.lastrowid)