Implementing class-like processing in pure SQL

Let's look at a somewhat more complex definition of a Blog class. This definition is repeated from Chapter 10, Serializing and Saving - JSON, YAML, Pickle, CSV, and XML, as well as Chapter 11,  Storing and Retrieving Objects via Shelve. This definition is as follows:

from dataclasses import dataclass, field, asdict

@dataclass
class Blog:

title: str
underline: str = field(init=False)

# Part of the persistence, not essential to the class.
_id: str = field(default="", init=False, compare=False)

def __post_init__(self) -> None:
self.underline = "=" * len(self.title)

This dataclass provides the essential title attribute for a blog. It has an optional attribute with the internal database ID assigned to the blog entry.

Here's the start of an Access class to retrieve Blog and Post objects:

class Access:

def open(self, path: Path) -> None:
self.database = sqlite3.connect(path)
self.database.row_factory = sqlite3.Row

def get_blog(self, id: str) -> Blog:
query_blog = """
SELECT * FROM blog WHERE id=?
"""
row = self.database.execute(query_blog, (id,)).fetchone()
blog = Blog(title=row["TITLE"])
blog._id = row["ID"]
return blog

This Access class has a method that creates a Blog object from the columns in the relational database. The __post_init__() method will create the expected underline attribute value. This shows the essential technique for working from relational data to an object.

Retrieving the Post instances associated with a Blog instance isn't trivial. It requires using an access object to fetch more rows from the database. It can't be done directly via some kind of attribute defined solely within the Blog class. We'll look at this in more depth when we look at the access layers and object-relational management (ORM).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset