program example;
{$mode objfpc}{$H+}
uses
dbutils, dSQLdbBroker, SysUtils, person;
type
// Specialization of TdGSQLdbOpf for handling TPerson entities
Topf = specialize TdGSQLdbOpf<TPerson>;
var
opf: Topf; // Object for managing operations on the `person` table
choice: Integer;
name: string;
age, id, newAge: Integer;
newName: string;
per: TPerson; // A single person entity
pers: Topf.TEntities; // A collection of person entities
begin
// Create an instance of the ORM operator for the `person` table
// `dbutils.con` provides the database connection, and 'person' is the table name
opf := Topf.Create(dbutils.con, 'person');
try
// Ensures the database table is ready for use
// `Empty` clears all data in the table (useful for testing scenarios)
opf.Empty;
opf.Apply; // Applies the changes to the database
// Main menu for interacting with the database
repeat
Writeln('1. Add Person');
Writeln('2. List Persons');
Writeln('3. Update Person');
Writeln('4. Delete Person');
Writeln('0. Exit');
Write('Enter your choice: ');
Readln(choice);
case choice of
1: // Add a new person to the database
begin
Write('Enter Name: ');
Readln(name);
Write('Enter Age: ');
Readln(age);
per := TPerson.Create; // Create a new entity instance
try
per.Name := name;
per.Age := age;
opf.Add(per); // Adds the entity to the database through the ORM
opf.Apply; // Persists the changes in the database
Writeln('Person added.');
finally
per.Free; // Free the entity after use
end;
end;
2: // Retrieve and list all persons in the database
begin
pers := Topf.TEntities.Create; // Initialize a collection for entities
Writeln('Listing all persons:');
opf.List(pers); // Fetch all records into the collection
for per in pers do
Writeln(Format('ID: %d | Name: %s | Age: %d', [per.ID, per.Name, per.Age]));
Writeln('Done.');
pers.Free; // Free the collection after use
end;
3: // Update an existing person's details
begin
Write('Enter ID to Update: ');
Readln(id);
Write('Enter New Name: ');
Readln(newName);
Write('Enter New Age: ');
Readln(newAge);
per := TPerson.Create; // Create a temporary entity to hold changes
try
per.ID := id;
per.Name := newName;
per.Age := newAge;
opf.Modify(per); // Update the record in the database
opf.Apply; // Commit the updates
Writeln('Person updated.');
finally
per.Free; // Free the entity after use
end;
end;
4: // Delete a person by their ID
begin
Write('Enter ID to Delete: ');
Readln(id);
per := TPerson.Create; // Create a temporary entity for deletion
try
per.ID := id;
opf.Remove(per); // Remove the record from the database
opf.Apply; // Commit the deletion
Writeln('Person deleted.');
finally
per.Free; // Free the entity after use
end;
end;
end;
until choice = 0; // Exit the program when the user chooses option 0
finally
opf.Free; // Release the ORM operator and associated resources
end;
Writeln('Exiting...');
end.