Wiki Page: load_tasks Method

The load_tasks method is a class method designed to retrieve tasks from a database based on specific criteria such as statuses, urgencies, and content. This method is versatile, allowing it to work with both CSV files and SQLite databases as data sources. Below, we explore the implementation details and functionality of the load_tasks method.

Method Definition

The load_tasks method is defined as follows:

@classmethod
def load_tasks(cls, statuses: list[TaskStatus]=None, urgencies: list[int]=None, content: str=""):
    """Load tasks matching specific criteria

    Args:
        statuses (list[TaskStatus], optional): Filter tasks with the specified statuses.
            Defaults to None, meaning no requirements on statuses
        urgencies (list[int], optional): Filter tasks with the specified urgencies.
            Defaults to None, meaning no requirements on urgencies
        content (str, optional): Filter tasks with the specified content (title, desc, or note).
            Defaults to "".

    Returns:
        list[Task]: The list of tasks that match the criteria
    """
    tasks = list()
    if app_db == TaskierDBOption.DB_CSV.value:
        with open(app_db, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                task_id, title, desc, urgency_str, status_str, note = row
                urgency = int(urgency_str)
                status = TaskStatus(int(status_str))
                if statuses and (status not in statuses):
                    continue
                if urgencies and (urgency not in urgencies):
                    continue
                if content and all([note.find(content) < 0, desc.find(content) < 0, title.find(content) < 0]):
                    continue
                task = cls(task_id, title, desc, urgency, status, note)
                tasks.append(task)
    else:
        # using the SQLite as the data source
        pass
    return tasks

CSV Data Source

When the data source is a CSV file, the method reads the file line by line, filtering tasks based on the provided criteria. It uses the find method to search for substrings within the task's title, description, and note.

SQLite Data Source

For SQLite databases, the method constructs an SQL statement to filter tasks. It uses the fetchall method to retrieve records that match the criteria. The SQL statement is dynamically constructed based on the presence of filtering criteria such as statuses, urgencies, and content.

Listing 14.6 Loading data from the SQLite database

@classmethod
def load_tasks(cls, statuses: list[TaskStatus]=None, urgencies: list[int]=None, content: str=""):
   """The docstring as before
   """
   tasks = list()
   if app_db == TaskierDBOption.DB_CSV.value:
       # csv-related code from [listing 14.3](https://livebook.manning.com/python-how-to/chapter-14/listing--14-3)
       pass
   else:
       with cls.con as con:
           if statuses is None:
               statuses = tuple(map(int, TaskStatus))
           else:
               statuses = tuple(statuses) * 2
           if urgencies is None:
               urgencies = tuple(range(1, 6))
           else:
               urgencies = tuple(urgencies) * 2
           sql_stmt = f"SELECT * FROM task WHERE status in {statuses} and urgency in {urgencies}"
           if content:
               sql_stmt += f" and ((completion_note LIKE '%{content}%') or (desc LIKE '%{content}%') or (title LIKE '%{content}%'))"
           cursor = con.cursor()
           cursor.execute(sql_stmt)
           tasks_tuple = cursor.fetchall()
           tasks = [Task(*x) for x in tasks_tuple]
   return tasks

Performance Considerations

The load_tasks method is decorated with a time-logging decorator to measure its execution time. Although the SQLite database generally outperforms the CSV file in terms of data-reading speed, the difference is minimal when dealing with small datasets.

Example Timings

Here are some example timings for loading tasks from both CSV and SQLite data sources:

# [Using the CSV file as the data source](https://livebook.manning.com/book/python-how-to/chapter-14/151)
*** load_tasks ends; used time: 0.0008411407 s
--- load_tasks starts
*** load_tasks ends; used time: 0.0005502701 s
--- load_tasks starts
*** load_tasks ends; used time: 0.0004429817 s

# [Using the SQLite as the data source](https://livebook.manning.com/book/python-how-to/chapter-14/151)
--- load_tasks starts
*** load_tasks ends; used time: 0.0003259182 s
--- load_tasks starts
*** load_tasks ends; used time: 0.0002837181 s
--- load_tasks starts
*** load_tasks ends; used time: 0.0004198551 s

These timings illustrate the efficiency of the load_tasks method in different scenarios, highlighting the slight performance advantage of using SQLite over CSV.