sabato 8 febbraio 2025

[EN] DMVCFramework Gotcha #2: Active Record

Active Record is an architectural design pattern introduced by Martin Fowler in his 2003 publication.

The Active Record pattern is built on the concept of abstracting a database table into a class that adheres to OOP principles. In this pattern, each class instance represents a single table row, while the class itself provides methods implementing all CRUD operations. Such a class encapsulates all database interaction logic, offering an object-oriented interface for data manipulation. It's worth noting that this pattern inherently creates coupling between the class structure and the underlying database table.

Key Features:

1. Database Encapsulation: All database connection details and SQL queries are encapsulated within the class

2. Data Validation: The class implements validation rules before executing database operations

3. Object Properties: Direct mapping to table columns

4. Object Relationships: Handled through methods that implement database relationships (one-to-many, many-to-many, etc.)

While Delphi itself doesn't implement Active Record natively, DMVCFramework (https://github.com/danieleteti/delphimvcframework) provides a robust implementation of this pattern.

I recently found Active Record particularly useful when developing a small application to process and store JSON data in a database. Specifically, I needed to handle JSON files generated by Anthropic from Claude.AI conversation exports.

After analyzing the JSON structure, I designed the necessary database tables. To illustrate Active Record's features, I'll focus on a specific part of the implementation.

I started by creating the Chat 'header' table, then defined its corresponding Entity in Delphi:

The entity serves as an abstraction of our database table. Let's examine its structure:

We define a class inheriting from TMVCActiveRecord:

TChats = class(TMVCActiveRecord)

TMVCActiveRecord is the framework's base class that provides all necessary data interaction methods. The entity definition's key feature lies in its field declarations, each decorated with Custom Attributes that define their behavior:

[MVCTable('chats')]: This Custom Attribute specifies which database table the class abstracts

[MVCTableField('chat_uuid', [foPrimaryKey])]: This Custom Attribute binds class fields to physical database table attributes

We create similar entities for each database table we need to interact with.

The implementation then involves reading the JSON (using the JsonDataObjects library, also available in DMVCFramework), iterating through it, and persisting the data to the database.

This code creates a new database record, but what we've covered is just a basic introduction to Active Record in DMVCFramework. There are many more features available. For instance, how do we check if a chat has already been processed?

While this example uses RQL (Resources Query Language), we could alternatively use Active Record's built-in methods, such as querying by primary key.

This practical implementation demonstrates how Active Record significantly simplifies data persistence, allowing developers to focus on business logic rather than database access details. The combination of DMVCFramework and Active Record has made JSON data import and management remarkably straightforward and efficient.

Though this example is relatively simple, Active Record in DMVCFramework supports more complex scenarios, including entity relationships, custom validations, and advanced querying capabilities.

For further exploration, I recommend reviewing the DMVCFramework documentation, which provides comprehensive examples and advanced use cases. Understanding and properly implementing this pattern can substantially improve productivity when developing Delphi applications requiring database interaction.

#codinglikeacoder

DMVCFramework Gotcha #2: Active Record

Active Record è un design pattern architetturale introdotto da Martin Fowler e descritto qui: Martin Fowler - 2003 .

Alla base del pattern Active Record vi è l'idea di astrarre una tabella del database rappresentandola con una classe; la classe seguirà i principi che caratterizzano il paradigma OOP. In questo pattern, ogni istanza della classe rappresenta una singola riga della tabella, mentre la classe stessa è specializzata con metodi che implementano tutte le operazioni CRUD. Una classe così strutturata incapsula tutta la logica necessaria per le operazioni di interazione con il database, creando un'interfaccia orientata agli oggetti per la manipolazione dei dati. È importante notare che questo pattern, per sua natura, crea un accoppiamento tra la struttura della classe e quella della tabella del database sottostante.

Alcune caratteristiche:

  1. Incapsulamento del database: Tutti i dettagli di connessione e query SQL sono nascosti all'interno della classe
  2. Validazione dei dati: La classe può implementare regole di validazione prima di eseguire operazioni sul database
  3. Proprietà dell'oggetto: Corrispondono direttamente alle colonne della tabella
  4. Relazioni tra oggetti: Possono essere gestite attraverso metodi che implementano le relazioni del database (one-to-many, many-to-many, etc.)

Delphi ad oggi non implementa Active Record.
DMVCFramework, invece,  ( https://github.com/danieleteti/delphimvcframework ) porta con se l'implementazione di Active Record.

Active Record mi è stato molto utile qualche giorno fa: avevo l'esigenza di scrivere un piccolo applicativo che prendesse in input un JSON, lo parserizzasse e memorizzasse le informazioni in esso contenute, in un Database. Il JSON in questione è il JSON generato da Anthropic dopo aver richiesto il download delle conversazioni fatte con Claude.AI.

Dopo aver analizzato la struttura del JSON, ho creato le tabelle.
Qui non vi mostro tutto il processo ma una parte di esso che mi permetta di mostrarvi qualche caratteristica di Active Record.

La prima tabella che ho creato è stata quella per la 'testata' della Chat:


In Delphi ho definito una Entity che rappresentasse la tabella:

L'entity così definita è l'astrazione della tabella che abbiamo definito nel database.
Analizziamola:

dichiariamo una classe derivata da TMVCActiveRecord: 

TChats = class(TMVCActiveRecord)

TMVCActiveRecord è la classe base definita nel framework e che implementa tutti quei metodi utili alla
interazione con i dati.
La caratteristica principale che notiamo nella definizione della entity, riguarda i fields della classe. 
Ognuno di essi è 'decoratocon un Custom Attribute che ne determina il comportamento:

[MVCTable('chats')] :è il Custom Attribute che ci permette di definire il nome della tabella del DB di cui questa classe è astrazione;
[MVCTableField('chat_uuid', [foPrimaryKey])]: è il Custom Attribute utilizzato per 'legare' il field della classe all'attributo
della tabella fisica del database.

Per ogni tabella del database con la quale necessitiamo interagire, creeremo una entity.

A questo punto non ci resta che leggere il Json (utilizzo la libreria JsonDataObjects, anch'essa
disponibile in DMVCFramework), iterare su di esso e memorizzarlo nel DB:

Grazie a questo codice, avrò nel database un nuovo record.

Quel che mostrato sino ad ora è solo una semplice introduzione ad Active Record implementato in 
DMVCFramework.
E sicuramente non è esaustivo di tutte le peculiarità implementate.
Ad esempio: come faccio a sapere se la chat che sto analizzando è stata già elaborata precendentemente?

In questo esempio ho utilizzato l'RQL (Resources Query Language), ma avrei potuto anche utilizzare un 
metodo di Active Record che, ad esempio, mi permette di interrogare il db cercando per chiave primaria...

Questo esempio pratico dimostra come Active Record semplifichi notevolmente le operazioni di persistenza
dei dati, permettendoci di concentrarci sulla logica di business piuttosto che sui dettagli di implementazione
dell'accesso al database. 
La combinazione di DMVCFramework e il pattern Active Record ha reso il processo di importazione e 
gestione dei dati JSON estremamente fluido ed efficiente. È importante notare che, nonostante l'esempio mostrato sia relativamente semplice, Active Record 
in DMVCFramework supporta scenari molto più complessi, incluse relazioni tra entità, validazioni 
personalizzate e query avanzate.
Per chi volesse approfondire l'argomento, consiglio di esplorare la documentazione di DMVCFramework,
che offre molti altri esempi e casi d'uso avanzati del pattern Active Record.
La comprensione di questo pattern e la sua corretta implementazione possono significativamente migliorare
la produttività nello sviluppo di applicazioni Delphi che necessitano di interazione con database. #codinglikeacoder

[EN] DMVCFramework Gotcha #2: Active Record

Active Record is an architectural design pattern introduced by Martin Fowler in his 2003 publication. The Active Record pattern is built on ...