HomeToolsAbout a20k

Data Access Pattern

What is it

Manages how an application interacts with its underlying data source, typically a database.

Aims to keep the software components cohesive while maintaining minimum coupling.

  • yields scalability and non-dependent database application

Main components:

  • Data table Gateway
  • Row Data Gateway
  • Data Mapper
  • Active Record
  • Repository
  • Data Access Object (DAO)

Table Data Gateway Pattern

Each table in the DB has a Class representing it.

  • All CRUD operations are executed through the Class for the specified table

Business model object interacts with the table data gateway class to store and retrieve data from the DB.

  • The gateway class contains methods to interact with the database, such as querying, inserting, updating, and deleting data.

Only one instance of Table Data Gateway can manage the data of all business model object instance of a specified type.

  • All database access for a specific table is centralized in the gateway class, keeping SQL queries separated from business logic.
# Gateway interacts with the table Person_Table <--> Person_Gateway # Table/Object Person |-> lastName |-> firstName # Gateway PersonGateway |-> find(id) |-> findForCompany(companyId) # find all person in company, returns Person |-> update(id, lastName, firstName) |-> insert(id, lastName, firstName)

Implementation Code Example

class UserGateway: def find(self, user_id): result = db.query(f"SELECT * FROM users WHERE id = {user_id}") return result def find_all(self): result = db.query("SELECT * FROM users") return result def insert(self, name, email): db.execute(f"INSERT INTO users (name, email) VALUES ('{name}', '{email}')") def update(self, user_id, name, email): db.execute(f"UPDATE users SET name = '{name}', email = '{email}' WHERE id = {user_id}") def delete(self, user_id): db.execute(f"DELETE FROM users WHERE id = {user_id}")

Row Data Gateway

© VincentVanKoh