To achieve the desired functionality of formatting each field based on a custom FmtProp attribute, we need to make several enhancements to your existing codebase. Below are the step-by-step instructions and code snippets to implement this feature effectively.
1. Define the FmtProp Attribute
First, we need to create a custom attribute FmtPropAttribute which will hold the TFormatType value. This attribute can be applied to the fields of your classes to specify the formatting type.
Update ORM_CustomAttributes Unit
Add the FmtPropAttribute to your ORM_CustomAttributes unit.
unit ORM_CustomAttributes;
{$TYPEINFO ON}
interface
uses
System.SysUtils, System.Classes, System.Rtti;
type
/// <summary>
/// Attribute to specify the database table associated with a class or field.
/// </summary>
TableAttribute = class(TCustomAttribute)
private
FTableName: string;
public
constructor Create(const ATableName: string);
property TableName: string read FTableName;
end;
/// <summary>
/// Attribute to mark a field as a primary key.
/// </summary>
PrimaryKeyAttribute = class(TCustomAttribute)
public
constructor Create;
end;
/// <summary>
/// Attribute to specify the database column associated with a field.
/// </summary>
RefColumnAttribute = class(TCustomAttribute)
private
FColumnName: string;
public
constructor Create(const AColumnName: string);
property ColumnName: string read FColumnName;
end;
/// <summary>
/// Attribute to specify the formatting type for a property.
/// </summary>
FmtPropAttribute = class(TCustomAttribute)
private
FFormatType: TFormatType;
public
constructor Create(AFormatType: TFormatType);
property FormatType: TFormatType read FFormatType;
end;
implementation
{ TableAttribute }
constructor TableAttribute.Create(const ATableName: string);
begin
inherited Create;
FTableName := ATableName;
end;
{ RefColumnAttribute }
constructor RefColumnAttribute.Create(const AColumnName: string);
begin
inherited Create;
FColumnName := AColumnName;
end;
{ PrimaryKeyAttribute }
constructor PrimaryKeyAttribute.Create;
begin
inherited Create;
end;
{ FmtPropAttribute }
constructor FmtPropAttribute.Create(AFormatType: TFormatType);
begin
inherited Create;
FFormatType := AFormatType;
end;
end.
2. Implement the GetFormattedText Method in TQryRecInfo
Next, we'll implement the GetFormattedText method within the TQryRecInfo class. This method will utilize RTTI to retrieve the FmtProp attribute (if defined) and format the property accordingly using the FormataInfo function. If the FmtProp attribute is not defined, it will use default formatting based on the property's data type.
Update orm_utils Unit
Add the GetFormattedText method to your TQryRecInfo class in the orm_utils unit.
unit orm_utils;
{$TYPEINFO ON}
interface
uses
System.Generics.Collections, Rtti, TypInfo, SysUtils, StrUtils, DateUtils, Math,
pixel_classes, System.Variants, ORM_CustomAttributes;
type
TQryRecInfo = class
private
FDirtyFields: TDictionary<string, Boolean>;
FPreviousValues: TDictionary<string, TValue>;
procedure Set_Info(Index: integer; const Value: TValue);
public
constructor Create;
destructor Destroy; override;
procedure Set_Info_NullableString(Index: integer; const Value: TNullable<string>);
procedure Set_Info_NullableInteger(Index: integer; const Value: TNullable<Integer>);
procedure Set_Info_NullableInt64(Index: integer; const Value: TNullable<Int64>);
procedure Set_Info_NullableExtended(Index: integer; const Value: TNullable<Extended>);
procedure Set_Info_NullableCurrency(Index: integer; const Value: TNullable<Currency>);
procedure Set_Info_NullableDateTime(Index: integer; const Value: TNullable<TDateTime>);
procedure Set_Info_NullableBoolean(Index: integer; const Value: TNullable<Boolean>);
procedure Set_Info_NullableVariant(Index: integer; const Value: TNullable<Variant>);
// Methods to handle dirty fields
function IsFieldDirty(const FieldName: string): Boolean;
procedure ClearDirtyFlags;
property DirtyFields: TDictionary<string, Boolean> read FDirtyFields;
// Methods to handle previous values
function GetPreviousValue(const FieldName: string): TValue;
procedure ClearPreviousValues;
property PreviousValues: TDictionary<string, TValue> read FPreviousValues;
/// <summary>
/// Returns the formatted text of the specified field based on the FmtProp attribute or default formatting.
/// </summary>
/// <param name="FieldName">The name of the field/property to format.</param>
/// <returns>A formatted string representation of the field's value.</returns>
function GetFormattedText(const FieldName: string): string;
end;
implementation
uses
ORM_CustomAttributes;
function FormataInfo(info: Variant; tipo: TFormatType): string;
begin
// Existing implementation...
if VarIsNull(info) or VarIsEmpty(info) then Exit('');
if VarType(info) = varUString then
begin
case tipo of
tiInteger: Exit(PegaInt(info).ToString);
tiMoney: Exit(FormatFloat('###,###.00', GetMoney(info)));
tiFloat: Exit(FloatToStr(PegaFloat(info)));
tiDate: Exit(FormatDateTime('dd/mm/yyyy', PegaData(info)));
tiDateTime: Exit(FormatDateTime('dd/mm/yyyy hh:mm:ss', PegaDataHora(info)));
tiBoolean: Exit(IIF(info, 'S', 'N'));
tiByteArray: Exit(ByteArrayToHex(info));
else Exit(VarToStr(info));
end;
end;
case tipo of
tiString: Result := VarToStr(info);
tiInteger: Result := integer(info).ToString;
tiMoney: Result := FormatFloat('###,###.00', Currency(info));
tiFloat: Result := FloatToStr(info);
tiBoolean: Result := string(IIF(Boolean(info), 'S', 'N'));
tiByteArray: Result := string(ByteArrayToHex(info));
tiDate:
begin
if VarType(info) in [varDate, varDouble] then
begin
if info = 0 then Exit('')
else if VarToDateTime(info) < EncodeDate(1900, 1, 1) then Exit('')
else Exit(FormatDateTime('dd/mm/yyyy', VarToDateTime(info)));
end
else raise Exception.Create('FormataInfo: A informação [' + VarToStr(info) + '] não pode ser tratada como tiDate');
end;
tiDateTime:
begin
if VarType(info) in [varDate, varDouble] then
begin
if info = 0 then Exit('')
else Exit(FormatDateTime('dd/mm/yyyy hh:mm:ss', VarToDateTime(info)));
end
else raise Exception.Create('FormataInfo: A informação [' + VarToStr(info) + '] não pode ser tratada como tiDateTime');
end;
else raise Exception.Create('FormataInfo: o [' + GetEnumName(TypeInfo(TFormatType), integer(tipo)) + '] não foi encontrado');
end;
end;
constructor TQryRecInfo.Create;
begin
inherited;
FDirtyFields := TDictionary<string, Boolean>.Create;
FPreviousValues := TDictionary<string, TValue>.Create;
end;
destructor TQryRecInfo.Destroy;
begin
FDirtyFields.Free;
FPreviousValues.Free;
inherited;
end;
procedure TQryRecInfo.Set_Info(Index: integer; const Value: TValue);
var
PropName: string;
PropKind: TTypeKind;
Ctx: TRttiContext;
Field: TRttiField;
OldValue: TValue;
begin
if not GetPropNameAndField(Self.ClassType, Index, PropName, PropKind) then
raise Exception.Create('Error: The index "' + Index.ToString + '" does not exist in class "' + ClassType.ClassName + '"');
Ctx := TRttiContext.Create;
Field := Ctx.GetType(Self.ClassType).GetField('_' + PropName);
if Assigned(Field) then
begin
// If the field is not yet dirty, store the previous value
if not FDirtyFields.ContainsKey(PropName) then
begin
OldValue := Field.GetValue(Self);
FPreviousValues.AddOrSetValue(PropName, OldValue);
end;
// Set the new value
Field.SetValue(Self, Value);
// Mark the property as dirty
FDirtyFields.AddOrSetValue(PropName, True);
end
else
raise Exception.Create('Error: Field "_' + PropName + '" not found.');
end;
procedure TQryRecInfo.Set_Info_NullableString(Index: integer; const Value: TNullable<string>);
begin
Set_Info(Index, TValue.From<TNullable<string>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableInteger(Index: integer; const Value: TNullable<Integer>);
begin
Set_Info(Index, TValue.From<TNullable<Integer>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableInt64(Index: integer; const Value: TNullable<Int64>);
begin
Set_Info(Index, TValue.From<TNullable<Int64>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableExtended(Index: integer; const Value: TNullable<Extended>);
begin
Set_Info(Index, TValue.From<TNullable<Extended>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableCurrency(Index: integer; const Value: TNullable<Currency>);
begin
Set_Info(Index, TValue.From<TNullable<Currency>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableDateTime(Index: integer; const Value: TNullable<TDateTime>);
begin
Set_Info(Index, TValue.From<TNullable<TDateTime>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableBoolean(Index: integer; const Value: TNullable<Boolean>);
begin
Set_Info(Index, TValue.From<TNullable<Boolean>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableVariant(Index: integer; const Value: TNullable<Variant>);
begin
Set_Info(Index, TValue.From<TNullable<Variant>>(Value));
end;
// Method to check if a field is dirty
function TQryRecInfo.IsFieldDirty(const FieldName: string): Boolean;
begin
Result := FDirtyFields.ContainsKey(FieldName);
end;
// Method to clear all dirty flags
procedure TQryRecInfo.ClearDirtyFlags;
begin
FDirtyFields.Clear;
end;
// Method to get the previous value of a property
function TQryRecInfo.GetPreviousValue(const FieldName: string): TValue;
begin
if FPreviousValues.TryGetValue(FieldName, Result) then
Exit;
// Return some default value or raise exception if not found
raise Exception.CreateFmt('No previous value found for field "%s".', [FieldName]);
end;
// Method to clear previous values
procedure TQryRecInfo.ClearPreviousValues;
begin
FPreviousValues.Clear;
end;
{ TQryRecInfo.GetFormattedText }
function TQryRecInfo.GetFormattedText(const FieldName: string): string;
var
RttiCtx: TRttiContext;
RttiType: TRttiType;
RttiProp: TRttiProperty;
Attr: FmtPropAttribute;
FormatType: TFormatType;
Value: TValue;
FormattedStr: string;
V: Variant;
begin
Result := '';
RttiCtx := TRttiContext.Create;
try
RttiType := RttiCtx.GetType(Self.ClassType);
RttiProp := RttiType.GetProperty(FieldName);
if not Assigned(RttiProp) then
raise Exception.CreateFmt('Property "%s" not found in class %s.', [FieldName, Self.ClassType.Name]);
// Get FmtProp attribute if exists
Attr := RttiProp.GetAttribute<FmtPropAttribute>;
if Assigned(Attr) then
FormatType := Attr.FormatType
else
begin
// Determine default format type based on property type
if RttiProp.PropertyType.Handle = TypeInfo(TNullable<String>) then
FormatType := tiString
else if RttiProp.PropertyType.Handle = TypeInfo(TNullable<Integer>) then
FormatType := tiInteger
else if RttiProp.PropertyType.Handle = TypeInfo(TNullable<Currency>) then
FormatType := tiMoney
else if RttiProp.PropertyType.Handle = TypeInfo(TNullable<TDateTime>) then
FormatType := tiDateTime
else if RttiProp.PropertyType.Handle = TypeInfo(TNullable<Boolean>) then
FormatType := tiBoolean
else
FormatType := tiNone; // Default or unsupported types
end;
// Get property value
Value := RttiProp.GetValue(Self);
// Handle TNullable<T>
if Value.IsType<TNullable<string>> then
begin
var Nullable := Value.AsType<TNullable<string>>;
if Nullable.HasValue then
V := Nullable.Value
else
Exit(''); // Null value, return empty string
end
else if Value.IsType<TNullable<Integer>> then
begin
var Nullable := Value.AsType<TNullable<Integer>>;
if Nullable.HasValue then
V := Nullable.Value
else
Exit('');
end
else if Value.IsType<TNullable<Currency>> then
begin
var Nullable := Value.AsType<TNullable<Currency>>;
if Nullable.HasValue then
V := Nullable.Value
else
Exit('');
end
else if Value.IsType<TNullable<TDateTime>> then
begin
var Nullable := Value.AsType<TNullable<TDateTime>>;
if Nullable.HasValue then
V := Nullable.Value
else
Exit('');
end
else if Value.IsType<TNullable<Boolean>> then
begin
var Nullable := Value.AsType<TNullable<Boolean>>;
if Nullable.HasValue then
V := Nullable.Value
else
Exit('');
end
else
begin
// Handle other TNullable types as needed
Exit('');
end;
// Call FormataInfo
FormattedStr := FormataInfo(V, FormatType);
Result := FormattedStr;
finally
RttiCtx.Free;
end;
end;
end.
Explanation of GetFormattedText Implementation:
-
RTTI Context Initialization:
- Creates an
TRttiContext to access RTTI information about the class and its properties.
-
Property Retrieval:
- Retrieves the property using the provided
FieldName.
- If the property does not exist, it raises an exception.
-
Attribute Checking:
- Checks if the
FmtPropAttribute is applied to the property.
- If it exists, it uses the specified
FormatType.
- If not, it determines the default
FormatType based on the property's data type.
-
Value Extraction:
- Extracts the value from the property.
- Checks if the
TNullable<T> has a value (HasValue).
- If
HasValue is False, it returns an empty string.
-
Formatting:
- Calls the
FormataInfo function with the extracted value and the determined FormatType.
- Returns the formatted string.
3. Update Your Models to Use the FmtProp Attribute
With the FmtPropAttribute defined and the GetFormattedText method implemented, you can now decorate your class fields with the FmtProp attribute to specify custom formatting.
Example: TEmployeeProject Class
Here’s how you can update your TEmployeeProject class to utilize the FmtProp attribute:
type
TEmployeeProject = class(TQryRecInfo)
private
[Table('employees'), PrimaryKey, RefColumn('emp_id')]
_EmployeeID: TNullable<Integer>;
[Table('employees'), PrimaryKey, RefColumn('dept_id')]
_DepartmentID: TNullable<Integer>;
[Table('employees'), RefColumn('emp_name')]
_EmployeeName: TNullable<String>;
[Table('projects'), PrimaryKey, RefColumn('proj_id')]
_ProjectID: TNullable<Integer>;
[Table('projects'), RefColumn('proj_name')]
_ProjectName: TNullable<String>;
[Table('projects'), RefColumn('proj_budget')]
_ProjectBudget: TNullable<Currency>;
[Table('projects'), RefColumn('proj_date'), FmtProp(tiDate)]
_ProjectDate: TNullable<TDateTime>;
[Table('projects'), RefColumn('proj_starttime'), FmtProp(tiDateTime)]
_ProjectStartMoment: TNullable<TDateTime>;
published
property EmployeeID: TNullable<Integer> index 0 read _EmployeeID write Set_Info_NullableInteger;
property DepartmentID: TNullable<Integer> index 1 read _DepartmentID write Set_Info_NullableInteger;
property EmployeeName: TNullable<String> index 2 read _EmployeeName write Set_Info_NullableString;
property ProjectID: TNullable<Integer> index 3 read _ProjectID write Set_Info_NullableInteger;
property ProjectName: TNullable<String> index 4 read _ProjectName write Set_Info_NullableString;
property ProjectBudget: TNullable<Currency> index 5 read _ProjectBudget write Set_Info_NullableCurrency;
property ProjectDate: TNullable<TDateTime> index 6 read _ProjectDate write Set_Info_NullableDateTime;
property ProjectStartMoment: TNullable<TDateTime> index 7 read _ProjectStartMoment write Set_Info_NullableDateTime;
end;
Usage Example:
var
EmployeeProject: TEmployeeProject;
begin
EmployeeProject := TEmployeeProject.Create;
try
// Assign values to the properties
EmployeeProject.ProjectDate := EncodeDateTime(2024, 2, 1, 1, 2, 3, 0);
WriteLn(EmployeeProject.GetFormattedText('ProjectDate')); // Outputs: "01/02/2024"
EmployeeProject.ProjectStartMoment := EncodeDateTime(2023, 12, 25, 10, 15, 50, 0);
WriteLn(EmployeeProject.GetFormattedText('ProjectStartMoment')); // Outputs: "25/12/2023 10:15:50"
EmployeeProject.DepartmentID := 27;
WriteLn(EmployeeProject.GetFormattedText('DepartmentID')); // Outputs: "27" // Default formatting
finally
EmployeeProject.Free;
end;
end;
4. Ensure Proper Integration with RTTI
To make sure that the custom attributes work seamlessly during runtime, ensure that RTTI is enabled in your project. This is already handled by the {$TYPEINFO ON} directive in your units, which enables RTTI for published properties.
5. Handling Unsupported Types (tiNone)
In cases where the FmtProp attribute is not defined (tiNone) or an unsupported type is encountered, the FormataInfo function currently raises an exception. You can modify the FormataInfo function to handle tiNone gracefully by providing a default string conversion.
Modify FormataInfo Function
Update the FormataInfo function to handle tiNone:
function FormataInfo(info: Variant; tipo: TFormatType): string;
begin
// Existing implementation...
case tipo of
tiString: Result := VarToStr(info);
tiInteger: Result := integer(info).ToString;
tiMoney: Result := FormatFloat('###,###.00', Currency(info));
tiFloat: Result := FloatToStr(info);
tiBoolean: Result := string(IIF(Boolean(info), 'S', 'N'));
tiByteArray: Result := string(ByteArrayToHex(info));
tiDate:
begin
if VarType(info) in [varDate, varDouble] then
begin
if info = 0 then Exit('')
else if VarToDateTime(info) < EncodeDate(1900, 1, 1) then Exit('')
else Exit(FormatDateTime('dd/mm/yyyy', VarToDateTime(info)));
end
else raise Exception.Create('FormataInfo: A informação [' + VarToStr(info) + '] não pode ser tratada como tiDate');
end;
tiDateTime:
begin
if VarType(info) in [varDate, varDouble] then
begin
if info = 0 then Exit('')
else Exit(FormatDateTime('dd/mm/yyyy hh:mm:ss', VarToDateTime(info)));
end
else raise Exception.Create('FormataInfo: A informação [' + VarToStr(info) + '] não pode ser tratada como tiDateTime');
end;
tiNone:
begin
// Default formatting
Result := VarToStr(info);
end;
else raise Exception.Create('FormataInfo: o [' + GetEnumName(TypeInfo(TFormatType), integer(tipo)) + '] não foi encontrado');
end;
end;
6. Comprehensive Example
To illustrate how everything works together, here's a comprehensive example combining all the pieces.
Full Example Usage
program ProjectDemo;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
orm_utils, // Contains TQryRecInfo and GetFormattedText
ORM_CustomAttributes, // Contains custom attributes including FmtPropAttribute
SQLParserEnhanced, // If needed for further ORM functionalities
pixel_classes; // Contains TNullable and related implementations
type
TEmployeeProject = class(TQryRecInfo)
private
[Table('employees'), PrimaryKey, RefColumn('emp_id')]
_EmployeeID: TNullable<Integer>;
[Table('employees'), PrimaryKey, RefColumn('dept_id')]
_DepartmentID: TNullable<Integer>;
[Table('employees'), RefColumn('emp_name')]
_EmployeeName: TNullable<String>;
[Table('projects'), PrimaryKey, RefColumn('proj_id')]
_ProjectID: TNullable<Integer>;
[Table('projects'), RefColumn('proj_name')]
_ProjectName: TNullable<String>;
[Table('projects'), RefColumn('proj_budget')]
_ProjectBudget: TNullable<Currency>;
[Table('projects'), RefColumn('proj_date'), FmtProp(tiDate)]
_ProjectDate: TNullable<TDateTime>;
[Table('projects'), RefColumn('proj_starttime'), FmtProp(tiDateTime)]
_ProjectStartMoment: TNullable<TDateTime>;
published
property EmployeeID: TNullable<Integer> index 0 read _EmployeeID write Set_Info_NullableInteger;
property DepartmentID: TNullable<Integer> index 1 read _DepartmentID write Set_Info_NullableInteger;
property EmployeeName: TNullable<String> index 2 read _EmployeeName write Set_Info_NullableString;
property ProjectID: TNullable<Integer> index 3 read _ProjectID write Set_Info_NullableInteger;
property ProjectName: TNullable<String> index 4 read _ProjectName write Set_Info_NullableString;
property ProjectBudget: TNullable<Currency> index 5 read _ProjectBudget write Set_Info_NullableCurrency;
property ProjectDate: TNullable<TDateTime> index 6 read _ProjectDate write Set_Info_NullableDateTime;
property ProjectStartMoment: TNullable<TDateTime> index 7 read _ProjectStartMoment write Set_Info_NullableDateTime;
end;
var
EmployeeProject: TEmployeeProject;
begin
try
EmployeeProject := TEmployeeProject.Create;
try
// Assign values to the properties
EmployeeProject.ProjectDate := EncodeDateTime(2024, 2, 1, 1, 2, 3, 0);
EmployeeProject.ProjectStartMoment := EncodeDateTime(2023, 12, 25, 10, 15, 50, 0);
EmployeeProject.DepartmentID := 27;
// Output formatted text
WriteLn(EmployeeProject.GetFormattedText('ProjectDate')); // Outputs: "01/02/2024"
WriteLn(EmployeeProject.GetFormattedText('ProjectStartMoment')); // Outputs: "25/12/2023 10:15:50"
WriteLn(EmployeeProject.GetFormattedText('DepartmentID')); // Outputs: "27"
finally
EmployeeProject.Free;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Expected Output:
01/02/2024
25/12/2023 10:15:50
27
7. Additional Considerations
Handling Additional TNullable<T> Types
If you have other TNullable<T> types in your models, ensure that the GetFormattedText method in TQryRecInfo appropriately handles them. You might need to extend the GetFormattedText method to include additional type checks and conversions.
Enhancing FormataInfo for More Types
The FormataInfo function can be further enhanced to support more complex formatting scenarios or additional TFormatType values as needed.
Error Handling
Ensure that proper error handling is in place, especially when dealing with RTTI operations and variant conversions. This will make your ORM more robust and easier to debug.
Performance Optimization
RTTI operations can be performance-intensive. If performance becomes a concern, consider caching RTTI metadata or optimizing the GetFormattedText method to reduce RTTI calls.
8. Complete Code Snippets for Reference
ORM_CustomAttributes Unit
unit ORM_CustomAttributes;
{$TYPEINFO ON}
interface
uses
System.SysUtils, System.Classes, System.Rtti;
type
/// <summary>
/// Attribute to specify the database table associated with a class or field.
/// </summary>
TableAttribute = class(TCustomAttribute)
private
FTableName: string;
public
constructor Create(const ATableName: string);
property TableName: string read FTableName;
end;
/// <summary>
/// Attribute to mark a field as a primary key.
/// </summary>
PrimaryKeyAttribute = class(TCustomAttribute)
public
constructor Create;
end;
/// <summary>
/// Attribute to specify the database column associated with a field.
/// </summary>
RefColumnAttribute = class(TCustomAttribute)
private
FColumnName: string;
public
constructor Create(const AColumnName: string);
property ColumnName: string read FColumnName;
end;
/// <summary>
/// Attribute to specify the formatting type for a property.
/// </summary>
FmtPropAttribute = class(TCustomAttribute)
private
FFormatType: TFormatType;
public
constructor Create(AFormatType: TFormatType);
property FormatType: TFormatType read FFormatType;
end;
implementation
{ TableAttribute }
constructor TableAttribute.Create(const ATableName: string);
begin
inherited Create;
FTableName := ATableName;
end;
{ RefColumnAttribute }
constructor RefColumnAttribute.Create(const AColumnName: string);
begin
inherited Create;
FColumnName := AColumnName;
end;
{ PrimaryKeyAttribute }
constructor PrimaryKeyAttribute.Create;
begin
inherited Create;
end;
{ FmtPropAttribute }
constructor FmtPropAttribute.Create(AFormatType: TFormatType);
begin
inherited Create;
FFormatType := AFormatType;
end;
end.
orm_utils Unit
unit orm_utils;
{$TYPEINFO ON}
interface
uses
System.Generics.Collections, Rtti, TypInfo, SysUtils, StrUtils, DateUtils, Math,
pixel_classes, System.Variants, ORM_CustomAttributes;
type
TQryRecInfo = class
private
FDirtyFields: TDictionary<string, Boolean>;
FPreviousValues: TDictionary<string, TValue>;
procedure Set_Info(Index: integer; const Value: TValue);
public
constructor Create;
destructor Destroy; override;
procedure Set_Info_NullableString(Index: integer; const Value: TNullable<string>);
procedure Set_Info_NullableInteger(Index: integer; const Value: TNullable<Integer>);
procedure Set_Info_NullableInt64(Index: integer; const Value: TNullable<Int64>);
procedure Set_Info_NullableExtended(Index: integer; const Value: TNullable<Extended>);
procedure Set_Info_NullableCurrency(Index: integer; const Value: TNullable<Currency>);
procedure Set_Info_NullableDateTime(Index: integer; const Value: TNullable<TDateTime>);
procedure Set_Info_NullableBoolean(Index: integer; const Value: TNullable<Boolean>);
procedure Set_Info_NullableVariant(Index: integer; const Value: TNullable<Variant>);
// Methods to handle dirty fields
function IsFieldDirty(const FieldName: string): Boolean;
procedure ClearDirtyFlags;
property DirtyFields: TDictionary<string, Boolean> read FDirtyFields;
// Methods to handle previous values
function GetPreviousValue(const FieldName: string): TValue;
procedure ClearPreviousValues;
property PreviousValues: TDictionary<string, TValue> read FPreviousValues;
/// <summary>
/// Returns the formatted text of the specified field based on the FmtProp attribute or default formatting.
/// </summary>
/// <param name="FieldName">The name of the field/property to format.</param>
/// <returns>A formatted string representation of the field's value.</returns>
function GetFormattedText(const FieldName: string): string;
end;
implementation
uses
ORM_CustomAttributes;
function FormataInfo(info: Variant; tipo: TFormatType): string;
begin
// Existing implementation...
if VarIsNull(info) or VarIsEmpty(info) then Exit('');
if VarType(info) = varUString then
begin
case tipo of
tiInteger: Exit(PegaInt(info).ToString);
tiMoney: Exit(FormatFloat('###,###.00', GetMoney(info)));
tiFloat: Exit(FloatToStr(PegaFloat(info)));
tiDate: Exit(FormatDateTime('dd/mm/yyyy', PegaData(info)));
tiDateTime: Exit(FormatDateTime('dd/mm/yyyy hh:mm:ss', PegaDataHora(info)));
tiBoolean: Exit(IIF(info, 'S', 'N'));
tiByteArray: Exit(ByteArrayToHex(info));
else Exit(VarToStr(info));
end;
end;
case tipo of
tiString: Result := VarToStr(info);
tiInteger: Result := integer(info).ToString;
tiMoney: Result := FormatFloat('###,###.00', Currency(info));
tiFloat: Result := FloatToStr(info);
tiBoolean: Result := string(IIF(Boolean(info), 'S', 'N'));
tiByteArray: Result := string(ByteArrayToHex(info));
tiDate:
begin
if VarType(info) in [varDate, varDouble] then
begin
if info = 0 then Exit('')
else if VarToDateTime(info) < EncodeDate(1900, 1, 1) then Exit('')
else Exit(FormatDateTime('dd/mm/yyyy', VarToDateTime(info)));
end
else raise Exception.Create('FormataInfo: A informação [' + VarToStr(info) + '] não pode ser tratada como tiDate');
end;
tiDateTime:
begin
if VarType(info) in [varDate, varDouble] then
begin
if info = 0 then Exit('')
else Exit(FormatDateTime('dd/mm/yyyy hh:mm:ss', VarToDateTime(info)));
end
else raise Exception.Create('FormataInfo: A informação [' + VarToStr(info) + '] não pode ser tratada como tiDateTime');
end;
tiNone:
begin
// Default formatting
Result := VarToStr(info);
end;
else raise Exception.Create('FormataInfo: o [' + GetEnumName(TypeInfo(TFormatType), integer(tipo)) + '] não foi encontrado');
end;
end;
constructor TQryRecInfo.Create;
begin
inherited;
FDirtyFields := TDictionary<string, Boolean>.Create;
FPreviousValues := TDictionary<string, TValue>.Create;
end;
destructor TQryRecInfo.Destroy;
begin
FDirtyFields.Free;
FPreviousValues.Free;
inherited;
end;
procedure TQryRecInfo.Set_Info(Index: integer; const Value: TValue);
var
PropName: string;
PropKind: TTypeKind;
Ctx: TRttiContext;
Field: TRttiField;
OldValue: TValue;
begin
if not GetPropNameAndField(Self.ClassType, Index, PropName, PropKind) then
raise Exception.Create('Error: The index "' + Index.ToString + '" does not exist in class "' + ClassType.ClassName + '"');
Ctx := TRttiContext.Create;
Field := Ctx.GetType(Self.ClassType).GetField('_' + PropName);
if Assigned(Field) then
begin
// If the field is not yet dirty, store the previous value
if not FDirtyFields.ContainsKey(PropName) then
begin
OldValue := Field.GetValue(Self);
FPreviousValues.AddOrSetValue(PropName, OldValue);
end;
// Set the new value
Field.SetValue(Self, Value);
// Mark the property as dirty
FDirtyFields.AddOrSetValue(PropName, True);
end
else
raise Exception.Create('Error: Field "_' + PropName + '" not found.');
end;
procedure TQryRecInfo.Set_Info_NullableString(Index: integer; const Value: TNullable<string>);
begin
Set_Info(Index, TValue.From<TNullable<string>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableInteger(Index: integer; const Value: TNullable<Integer>);
begin
Set_Info(Index, TValue.From<TNullable<Integer>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableInt64(Index: integer; const Value: TNullable<Int64>);
begin
Set_Info(Index, TValue.From<TNullable<Int64>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableExtended(Index: integer; const Value: TNullable<Extended>);
begin
Set_Info(Index, TValue.From<TNullable<Extended>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableCurrency(Index: integer; const Value: TNullable<Currency>);
begin
Set_Info(Index, TValue.From<TNullable<Currency>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableDateTime(Index: integer; const Value: TNullable<TDateTime>);
begin
Set_Info(Index, TValue.From<TNullable<TDateTime>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableBoolean(Index: integer; const Value: TNullable<Boolean>);
begin
Set_Info(Index, TValue.From<TNullable<Boolean>>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableVariant(Index: integer; const Value: TNullable<Variant>);
begin
Set_Info(Index, TValue.From<TNullable<Variant>>(Value));
end;
// Method to check if a field is dirty
function TQryRecInfo.IsFieldDirty(const FieldName: string): Boolean;
begin
Result := FDirtyFields.ContainsKey(FieldName);
end;
// Method to clear all dirty flags
procedure TQryRecInfo.ClearDirtyFlags;
begin
FDirtyFields.Clear;
end;
// Method to get the previous value of a property
function TQryRecInfo.GetPreviousValue(const FieldName: string): TValue;
begin
if FPreviousValues.TryGetValue(FieldName, Result) then
Exit;
// Return some default value or raise exception if not found
raise Exception.CreateFmt('No previous value found for field "%s".', [FieldName]);
end;
// Method to clear previous values
procedure TQryRecInfo.ClearPreviousValues;
begin
FPreviousValues.Clear;
end;
{ TQryRecInfo.GetFormattedText }
function TQryRecInfo.GetFormattedText(const FieldName: string): string;
var
RttiCtx: TRttiContext;
RttiType: TRttiType;
RttiProp: TRttiProperty;
Attr: FmtPropAttribute;
FormatType: TFormatType;
Value: TValue;
FormattedStr: string;
V: Variant;
begin
Result := '';
RttiCtx := TRttiContext.Create;
try
RttiType := RttiCtx.GetType(Self.ClassType);
RttiProp := RttiType.GetProperty(FieldName);
if not Assigned(RttiProp) then
raise Exception.CreateFmt('Property "%s" not found in class %s.', [FieldName, Self.ClassType.Name]);
// Get FmtProp attribute if exists
Attr := RttiProp.GetAttribute<FmtPropAttribute>;
if Assigned(Attr) then
FormatType := Attr.FormatType
else
begin
// Determine default format type based on property type
if RttiProp.PropertyType.Handle = TypeInfo(TNullable<String>) then
FormatType := tiString
else if RttiProp.PropertyType.Handle = TypeInfo(TNullable<Integer>) then
FormatType := tiInteger
else if RttiProp.PropertyType.Handle = TypeInfo(TNullable<Currency>) then
FormatType := tiMoney
else if RttiProp.PropertyType.Handle = TypeInfo(TNullable<TDateTime>) then
FormatType := tiDateTime
else if RttiProp.PropertyType.Handle = TypeInfo(TNullable<Boolean>) then
FormatType := tiBoolean
else
FormatType := tiNone; // Default or unsupported types
end;
// Get property value
Value := RttiProp.GetValue(Self);
// Handle TNullable<T>
if Value.IsType<TNullable<string>> then
begin
var Nullable := Value.AsType<TNullable<string>>;
if Nullable.HasValue then
V := Nullable.Value
else
Exit(''); // Null value, return empty string
end
else if Value.IsType<TNullable<Integer>> then
begin
var Nullable := Value.AsType<TNullable<Integer>>;
if Nullable.HasValue then
V := Nullable.Value
else
Exit('');
end
else if Value.IsType<TNullable<Currency>> then
begin
var Nullable := Value.AsType<TNullable<Currency>>;
if Nullable.HasValue then
V := Nullable.Value
else
Exit('');
end
else if Value.IsType<TNullable<TDateTime>> then
begin
var Nullable := Value.AsType<TNullable<TDateTime>>;
if Nullable.HasValue then
V := Nullable.Value
else
Exit('');
end
else if Value.IsType<TNullable<Boolean>> then
begin
var Nullable := Value.AsType<TNullable<Boolean>>;
if Nullable.HasValue then
V := Nullable.Value
else
Exit('');
end
else
begin
// Handle other TNullable types as needed
Exit('');
end;
// Call FormataInfo
FormattedStr := FormataInfo(V, FormatType);
Result := FormattedStr;
finally
RttiCtx.Free;
end;
end;
end.
pixel_classes Unit
Ensure that your pixel_classes unit defines the TNullable<T> record with the necessary operators as you've already implemented.
unit pixel_classes;
interface
uses
System.SysUtils, Rtti, TypInfo;
{$TYPEINFO ON}
type
TNullValue = record
end;
TNullable<T> = record
public
Value: T;
HasValue: Boolean;
class operator Implicit(const AValue: T): TNullable<T>;
class operator Implicit(const AValue: TNullable<T>): T;
class operator Implicit(const AValue: TNullValue): TNullable<T>;
class operator Explicit(const AValue: T): TNullable<T>;
// Equality operators
class operator Equal(const A: TNullable<T>; const B: TNullValue): Boolean;
class operator NotEqual(const A: TNullable<T>; const B: TNullValue): Boolean;
end;
var
NullValue: TNullValue;
implementation
class operator TNullable<T>.Implicit(const AValue: T): TNullable<T>;
begin
Result.Value := AValue;
Result.HasValue := True;
end;
class operator TNullable<T>.Implicit(const AValue: TNullable<T>): T;
begin
if AValue.HasValue then
Result := AValue.Value
else
Result := Default(T); // or raise an exception
end;
class operator TNullable<T>.Implicit(const AValue: TNullValue): TNullable<T>;
begin
Result.Value := Default(T);
Result.HasValue := False;
end;
class operator TNullable<T>.Explicit(const AValue: T): TNullable<T>;
begin
Result.Value := AValue;
Result.HasValue := True;
end;
// Equality operators
class operator TNullable<T>.Equal(const A: TNullable<T>; const B: TNullValue): Boolean;
begin
Result := not A.HasValue;
end;
class operator TNullable<T>.NotEqual(const A: TNullable<T>; const B: TNullValue): Boolean;
begin
Result := A.HasValue;
end;
end.
SQLParserEnhanced and ORM_GenerateDelphiClassFromQuery Units
These units are related to parsing SQL and generating Delphi classes from queries. Ensure they are correctly implemented and integrated if you plan to auto-generate classes based on SQL queries. However, for the current functionality of formatting properties, they are not directly involved.
9. Testing the Implementation
After implementing the above changes, it's crucial to test the functionality to ensure that the formatting works as expected.
Test Case
program TestFormat;
{$APPTYPE CONSOLE}
uses
SysUtils,
orm_utils;
type
TEmployeeProject = class(TQryRecInfo)
private
[Table('employees'), PrimaryKey, RefColumn('emp_id')]
_EmployeeID: TNullable<Integer>;
[Table('employees'), PrimaryKey, RefColumn('dept_id')]
_DepartmentID: TNullable<Integer>;
[Table('employees'), RefColumn('emp_name')]
_EmployeeName: TNullable<String>;
[Table('projects'), PrimaryKey, RefColumn('proj_id')]
_ProjectID: TNullable<Integer>;
[Table('projects'), RefColumn('proj_name')]
_ProjectName: TNullable<String>;
[Table('projects'), RefColumn('proj_budget')]
_ProjectBudget: TNullable<Currency>;
[Table('projects'), RefColumn('proj_date'), FmtProp(tiDate)]
_ProjectDate: TNullable<TDateTime>;
[Table('projects'), RefColumn('proj_starttime'), FmtProp(tiDateTime)]
_ProjectStartMoment: TNullable<TDateTime>;
published
property EmployeeID: TNullable<Integer> index 0 read _EmployeeID write Set_Info_NullableInteger;
property DepartmentID: TNullable<Integer> index 1 read _DepartmentID write Set_Info_NullableInteger;
property EmployeeName: TNullable<String> index 2 read _EmployeeName write Set_Info_NullableString;
property ProjectID: TNullable<Integer> index 3 read _ProjectID write Set_Info_NullableInteger;
property ProjectName: TNullable<String> index 4 read _ProjectName write Set_Info_NullableString;
property ProjectBudget: TNullable<Currency> index 5 read _ProjectBudget write Set_Info_NullableCurrency;
property ProjectDate: TNullable<TDateTime> index 6 read _ProjectDate write Set_Info_NullableDateTime;
property ProjectStartMoment: TNullable<TDateTime> index 7 read _ProjectStartMoment write Set_Info_NullableDateTime;
end;
var
EmployeeProject: TEmployeeProject;
begin
try
EmployeeProject := TEmployeeProject.Create;
try
// Assign values
EmployeeProject.ProjectDate := EncodeDateTime(2024, 2, 1, 1, 2, 3, 0);
EmployeeProject.ProjectStartMoment := EncodeDateTime(2023, 12, 25, 10, 15, 50, 0);
EmployeeProject.DepartmentID := 27;
// Display formatted texts
Writeln(EmployeeProject.GetFormattedText('ProjectDate')); // Expected: "01/02/2024"
Writeln(EmployeeProject.GetFormattedText('ProjectStartMoment')); // Expected: "25/12/2023 10:15:50"
Writeln(EmployeeProject.GetFormattedText('DepartmentID')); // Expected: "27" (Default formatting)
finally
EmployeeProject.Free;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Run the Test Case
Compile and run the TestFormat program. The expected output should be:
01/02/2024
25/12/2023 10:15:50
27
10. Conclusion
By defining a custom FmtPropAttribute and implementing the GetFormattedText method using RTTI, you've successfully extended your ORM to support custom text formatting for each field. This approach ensures flexibility and maintains clean separation between data representation and presentation formatting.
Feel free to further enhance the functionality by supporting more TFormatType values, handling additional data types, or optimizing the RTTI usage for better performance.