// TORMBind_Component_QryRec_Dictionary is used to map each TQryRecInfo descendant property to its respective TComponent, for example:
TEmployee1 is an instance of a TQryRecInfo descendant.
a TLabel TComponent "EmpName" maps to the property "EmployeeName" of TEmployee1
a TLabel TComponent "EmpSalary" maps to the property "Salary" of TEmployee1
a TDatePicker TComponent "BirthDay" maps to the property "DateOfBirth" of TEmployee1
For TEmployee1 I want choose to "bind" some of its properties to the corresponding TComponent that I choose, like the above example.
Something like:
TEmployee1.Bind('EmployeeName', EmpName);
TEmployee1.Bind('Salary', EmpSalary);
TEmployee1.Bind('DateOfBirth', BirthDay);
I need this to operate to perform bidirectional update, following some rules:
if the TQryRecInfo descendant property is mapped to a TEdit, then this property maps to the TEdit.Text
if the TQryRecInfo descendant property is mapped to a TLabel, then this property maps to the TLabel.Caption
if the TQryRecInfo descendant property is mapped to a TDatePicker, then this property maps to the TDatePicker.Date
and so on...
When the TQryRecInfo descendant property is not a string, but it should map to a string TComponent property, then use GetFormattedText to convert to its string representation
Then create some methods to perform the bidirectional binding between the TComponent property changes and its corresponding TQryRecInfo descendant property.
Create methods to Bind and Unbind manually.
Also create methods to bind all the TQryRecInfo descendant properties to the respective TComponents that have matching Hint contents to the TQryRecInfo descendant property name.
Perform the mapping using something like:
type
TComponentMapping = record
Mapped_TQryRecInfo_Instance: TObject;
Mapped_Property: string;
end;
type
TORMBind_Component_QryRec_Dictionary = TDictionary<TComponent, TComponentMapping>;
unit pixel_classes;
interface
uses
System.SysUtils, Rtti, TypInfo;
{$TYPEINFO ON}
type
TZString = type string;
type
TNullValue = record
end;
TNullable<T{: record}> = record
public
Value: T;
HasValue: Boolean;
code
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>;
// add these...
class operator Equal(const A: TNullable<T>; const B: TNullValue): Boolean;
class operator NotEqual(const A: TNullable<T>; const B: TNullValue): Boolean;
Assistant
end;
var NullValue: TNullValue;
implementation
class operator TNullable.Implicit(const AValue: T): TNullable;
begin
Result.Value := AValue;
Result.HasValue := True;
end;
class operator TNullable.Implicit(const AValue: TNullable): T;
begin
if AValue.HasValue then
Result := AValue.Value
else
Result := Default(T); // or raise an exception
end;
class operator TNullable.Implicit(const AValue: TNullValue): TNullable;
begin
Result.Value := Default(T);
Result.HasValue := False;
end;
class operator TNullable.Explicit(const AValue: T): TNullable;
begin
Result.Value := AValue;
Result.HasValue := True;
end;
class operator TNullable.Equal(const A: TNullable; const B: TNullValue): Boolean;
begin
Result := not A.HasValue;
end;
class operator TNullable.NotEqual(const A: TNullable; const B: TNullValue): Boolean;
begin
Result := A.HasValue;
end;
///
/// Attribute to specify the database table associated with a class or field.
///
TableAttribute = class(TCustomAttribute)
private
FTableName: string;
public
constructor Create(const ATableName: string);
property TableName: string read FTableName;
end;
///
/// Attribute to mark a field as a primary key.
///
PrimaryKeyAttribute = class(TCustomAttribute)
public
constructor Create;
end;
///
/// Attribute to specify the database column associated with a field.
///
RefColumnAttribute = class(TCustomAttribute)
private
FColumnName: string;
public
constructor Create(const AColumnName: string);
property ColumnName: string read FColumnName;
end;
///
/// Attribute to specify the formatting of a field.
///
FmtPropAttribute = class(TCustomAttribute)
private
FFormatType: TFormatType;
public
constructor Create(AFormatType: TFormatType);
property FormatType: TFormatType read FFormatType;
end;
///
/// Attribute to specify the column index of a property in a TStringGrid.
///
GridColumnAttribute = class(TCustomAttribute)
private
FColumnIndex: Integer;
public
constructor Create(AColumnIndex: Integer);
property ColumnIndex: Integer read FColumnIndex;
end;
///
/// Attribute to specify the TComponent a property is mapped to.
///
ComponentMappingAttribute = class(TCustomAttribute)
private
FComponentName: string;
public
constructor Create(const AComponentName: string);
property ComponentName: string read FComponentName;
end;
uses
System.SysUtils,
System.Classes,
System.Generics.Collections,
System.Rtti,
System.TypInfo,
Data.DB,
Uni,
VCL.Grids, // for TAdvStringGrid
AdvGrid, // for TAdvStringGrid
Vcl.Controls,
Vcl.StdCtrls,
pixel_classes,
orm_customattributes;
type
EORMUtilsException = class(Exception);
///
/// Base class for query record information
/// Use descendants of this class to represent specific database records.
///
TQryRecInfo = class
private
FDirtyFields: TDictionary<string, Boolean>;
FPreviousValues: TDictionary<string, TValue>;
FComponents: TDictionary<string, TComponent>;
procedure SetInfo(Index: Integer; const Value: TValue);
procedure UpdateComponent(const PropName: string; const Value: TValue);
procedure UpdateComponents;
public
constructor Create;
destructor Destroy; override;
code
// Methods to set nullable fields
procedure SetInfoNullableString(Index: Integer; const Value: TNullable<string>);
procedure SetInfoNullableInteger(Index: Integer; const Value: TNullable<Integer>);
procedure SetInfoNullableInt64(Index: Integer; const Value: TNullable<Int64>);
procedure SetInfoNullableExtended(Index: Integer; const Value: TNullable<Extended>);
procedure SetInfoNullableCurrency(Index: Integer; const Value: TNullable<Currency>);
procedure SetInfoNullableDateTime(Index: Integer; const Value: TNullable<TDateTime>);
procedure SetInfoNullableBoolean(Index: Integer; const Value: TNullable<Boolean>);
procedure SetInfoNullableVariant(Index: Integer; const Value: TNullable<Variant>);
// Methods to set non-nullable simple types
procedure SetInfoCurrency(Index: Integer; const Value: Currency);
procedure SetInfoString(Index: Integer; const Value: string);
procedure SetInfoInteger(Index: Integer; const Value: Integer);
procedure SetInfoInt64(Index: Integer; const Value: Int64);
procedure SetInfoExtended(Index: Integer; const Value: Extended);
procedure SetInfoDateTime(Index: Integer; const Value: TDateTime);
procedure SetInfoBoolean(Index: Integer; const Value: Boolean);
procedure SetInfoVariant(Index: Integer; const Value: 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;
// Method to handle mapping to components
procedure MapToComponent(const PropName: string; Component: TComponent);
/// <summary>
/// Retrieves the formatted text for a given field based on the FmtProp attribute.
/// </summary>
function GetFormattedText(const FieldName: string): string;
/// <summary>
/// Fetches data for this record from the database based on the provided SQL.
/// </summary>
procedure Fetch(DBConn: TUniConnection; const QryTxt: string);
end;
///
/// Generic class to handle arrays of TQryRecInfo descendants.
///
TQryRecArray<T: class, constructor> = class
private
FQryRecInfoList: TObjectList;
FFilterSQL: string;
FDBConn: TUniConnection;
FGrid: TAdvStringGrid;
FColumnMapping: TDictionary<string, Integer>;
function GetCount: Integer;
procedure UpdateGrid;
procedure GridToRecInfo(ACol, ARow: Integer);
public
constructor Create;
destructor Destroy; override;
code
/// <summary>
/// Fetches all records based on the provided SQL text and populates the array.
/// </summary>
/// <param name="QryTxt">The base SQL query text.</param>
procedure FetchAllInstance(DBConn: TUniConnection; const QryTxt: string);
/// <summary>
/// Clears any SQL filters applied.
/// </summary>
procedure ClearFilter;
/// <summary>
/// Accesses a record at the specified index.
/// </summary>
/// <param name="Index">The zero-based index of the record.</param>
/// <returns>The record at the specified index.</returns>
function Rec(Index: Integer): T;
/// <summary>
/// Number of records in the array.
/// </summary>
property RecCount: Integer read GetCount;
/// <summary>
/// Database connection used for fetching records.
/// </summary>
property DBConn: TUniConnection read FDBConn write FDBConn;
/// <summary>
/// Map of property names to specific grid columns by name.
/// </summary>
procedure MapToGrid(AGrid: TAdvStringGrid; const PropName: string; const ColumnName: string);
/// <summary>
/// Additional SQL filter to apply to the query.
/// </summary>
property SQLFilter: string read FFilterSQL write FFilterSQL;
/// <summary>
/// Provides support for for-in loops by returning an enumerator.
/// </summary>
function GetEnumerator: TEnumerator<T>;
/// <summary>
/// Factory method to create and fetch records in a single step.
/// </summary>
/// <param name="DBConn">Database connection.</param>
/// <param name="QryTxt">SQL query text.</param>
/// <returns>Populated instance of TQryRecArray<T>.</returns>
class function FetchAll(DBConn: TUniConnection; const QryTxt: string): TQryRecArray<T>; static;
end;
// Example descendant of TQryRecInfo (You can create your own)
TDynRec = class(TQryRecInfo)
// Define additional properties as needed
end;
implementation
uses
System.Variants,
StrUtils,
pixel_utils; // Ensure this unit is in your project and properly implemented
destructor TQryRecInfo.Destroy;
begin
FDirtyFields.Free;
FPreviousValues.Free;
FComponents.Free;
inherited;
end;
procedure TQryRecInfo.ClearDirtyFlags;
begin
FDirtyFields.Clear;
end;
procedure TQryRecInfo.ClearPreviousValues;
begin
FPreviousValues.Clear;
end;
function TQryRecInfo.IsFieldDirty(const FieldName: string): Boolean;
begin
Result := FDirtyFields.ContainsKey(FieldName) and FDirtyFields[FieldName];
end;
function TQryRecInfo.GetPreviousValue(const FieldName: string): TValue;
begin
if not FPreviousValues.TryGetValue(FieldName, Result) then
raise EORMUtilsException.CreateFmt('No previous value found for field "%s".', [FieldName]);
end;
function FormataInfo(info: Variant; tipo: TFormatType): string;
begin
if VarIsNull(info) or VarIsEmpty(info) then
Exit('');
case tipo of
tiString:
Result := VarToStr(info);
tiInteger:
Result := IntToStr(Integer(info));
tiMoney:
Result := FormatFloat(FMT_MONEY, Currency(info));
tiFloat:
Result := FloatToStr(info);
tiDate:
if VarIsType(info, [varDate, varDouble]) then
begin
if VarToDateTime(info) < EncodeDate(1900, 1, 1) then
Result := ''
else
Result := FormatDateTime('dd/mm/yyyy', VarToDateTime(info));
end
else
raise EORMUtilsException.CreateFmt('FormataInfo: Cannot treat information [%s] as tiDate.', [VarToStr(info)]);
tiDateTime:
if VarIsType(info, [varDate, varDouble]) then
begin
if VarToDateTime(info) = 0 then
Result := ''
else
Result := FormatDateTime('dd/mm/yyyy hh:mm:ss', VarToDateTime(info));
end
else
raise EORMUtilsException.CreateFmt('FormataInfo: Cannot treat information [%s] as tiDateTime.', [VarToStr(info)]);
tiBoolean:
Result := IfThen(Boolean(info), 'S', 'N');
tiByteArray:
Result := ByteArrayToHex(info);
tiNone:
Result := '';
else
raise EORMUtilsException.CreateFmt('FormataInfo: Format type [%s] not recognized.', [GetEnumName(TypeInfo(TFormatType), Integer(tipo))]);
end;
end;
// Find the property by name
Prop := RttiType.GetProperty(FieldName);
if not Assigned(Prop) then
raise EORMUtilsException.CreateFmt('Property "%s" not found.', [FieldName]);
// Get the value of the property
Value := Prop.GetValue(Self);
FmtType := tiNone;
// Check for FmtProp attribute on the property
for Attr in Prop.GetAttributes do
begin
if Attr is FmtPropAttribute then
begin
FmtAttr := FmtPropAttribute(Attr);
FmtType := FmtAttr.FormatType;
Break;
end;
end;
// If not found on property, check on the corresponding field
if FmtType = tiNone then
begin
Field := RttiType.GetField('_' + FieldName);
if Assigned(Field) then
begin
for Attr in Field.GetAttributes do
begin
if Attr is FmtPropAttribute then
begin
FmtAttr := FmtPropAttribute(Attr);
FmtType := FmtAttr.FormatType;
Break;
end;
end;
end;
end;
// Determine default FmtType based on property type if not set by attribute
if FmtType = tiNone then
begin
UnderlyingType := Prop.PropertyType;
// Handle TNullable<T>
if UnderlyingType.TypeKind = tkRecord then
begin
ValueField := UnderlyingType.GetField('Value');
if Assigned(ValueField) then
UnderlyingType := ValueField.FieldType;
end;
case UnderlyingType.TypeKind of
tkInteger, tkInt64:
FmtType := tiInteger;
tkFloat:
if UnderlyingType.Handle = TypeInfo(TDateTime) then
FmtType := tiDateTime
else
FmtType := tiFloat;
tkString, tkLString, tkWString, tkUString:
FmtType := tiString;
tkEnumeration:
if UnderlyingType.Handle = TypeInfo(Boolean) then
FmtType := tiBoolean
else
FmtType := tiString;
tkVariant:
FmtType := tiString;
else
FmtType := tiNone;
end;
end;
// Extract actual value from TNullable<T> if necessary
if Value.Kind = tkRecord then
begin
// Assuming TNullable<T> has 'HasValue' and 'Value' fields
UnderlyingType := Prop.PropertyType;
HasValueField := UnderlyingType.GetField('HasValue');
ValueField := UnderlyingType.GetField('Value');
if Assigned(HasValueField) and Assigned(ValueField) then
begin
HasValue := HasValueField.GetValue(Value.GetReferenceToRawData).AsBoolean;
if HasValue then
begin
ActualValue := ValueField.GetValue(Value.GetReferenceToRawData);
// Format the actual value
Result := FormataInfo(ActualValue.AsVariant, FmtType);
end
else
Result := '';
end
else
begin
// Not TNullable<T>, handle value directly
if not Value.IsEmpty then
Result := FormataInfo(Value.AsVariant, FmtType)
else
Result := '';
end;
end
else
begin
// Not a record, handle value directly
if not Value.IsEmpty then
Result := FormataInfo(Value.AsVariant, FmtType)
else
Result := '';
end;
finally
// No need to free TRttiContext as it's a record
end;
end;
procedure TQryRecInfo.UpdateComponent(const PropName: string; const Value: TValue);
var
Component: TComponent;
begin
if FComponents.TryGetValue(PropName, Component) then
begin
if Component is TEdit then
TEdit(Component).Text := Value.ToString
else if Component is TLabel then
TLabel(Component).Caption := Value.ToString
else if Component is TButton then
TButton(Component).Caption := Value.ToString;
// Add more component types if necessary
end;
end;
procedure TQryRecInfo.UpdateComponents;
var
PropName: string;
Value: TValue;
Ctx: TRttiContext;
RttiType: TRttiType;
RttiProp: TRttiProperty;
begin
Ctx := TRttiContext.Create;
try
RttiType := Ctx.GetType(Self.ClassType);
if RttiType <> nil then
begin
for PropName in FComponents.Keys do
begin
RttiProp := RttiType.GetProperty(PropName);
if (RttiProp <> nil) and (RttiProp.Visibility = mvPublished) then
begin
if RttiProp.PropertyType.TypeKind = tkClass then
begin
Value := RttiProp.GetValue(Self);
UpdateComponent(PropName, Value);
end
else
// Handle other property types or log a message
end;
end;
end;
finally
Ctx.Free;
end;
end;
procedure TQryRecInfo.Fetch(DBConn: TUniConnection; const QryTxt: string);
var
qr: TUniQuery;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
ORMFieldName: string;
begin
if not Assigned(DBConn) or Trim(QryTxt).IsEmpty then
Exit;
if qr.RecordCount > 0 then
begin
Ctx := TRttiContext.Create;
try
ObjType := Ctx.GetType(Self.ClassType);
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
// Attempt to find the corresponding field in the query
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue; // Field not found, skip
ORMFieldName := '_' + Prop.Name;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
// Expecting TNullable<T>
// Attempt to find the backing field for the nullable property
if ObjType.GetField(ORMFieldName) = nil then
Continue; // Backing field not found, skip
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
// Use RTTI to determine the generic type parameter
if Field.IsNull then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Variant>>(NullValue))
else
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Variant>>(Field.Value))
else
raise EORMUtilsException.CreateFmt('Unsupported TNullable type: %s', [Prop.PropertyType.Name]);
end;
end
else
raise EORMUtilsException.CreateFmt('Unsupported record type: %s', [Prop.PropertyType.Name]);
end
else
begin
// Handle non-nullable types
case Prop.PropertyType.TypeKind of
tkString, tkLString, tkWString, tkUString:
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsString);
tkInteger:
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsInteger);
tkInt64:
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsCurrency)
else
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsFloat);
tkVariant:
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsBoolean)
else
raise EORMUtilsException.CreateFmt('Unsupported enumeration type: %s', [Prop.PropertyType.Name]);
else
// Add additional handling for other types if necessary
end;
end;
end;
finally
// No need to free TRttiContext as it's a record
end;
UpdateComponents;
end;
finally
qr.Free;
end;
end;
procedure TQryRecInfo.SetInfo(Index: Integer; const Value: TValue);
var
PropName: string;
PropKind: TTypeKind;
Ctx: TRttiContext;
Prop: TRttiProperty;
Field: TRttiField;
OldValue: TValue;
begin
// Retrieve property name and kind based on index
// Assuming that the index corresponds to the property order
Ctx := TRttiContext.Create;
try
Prop := Ctx.GetType(Self.ClassType).GetProperties()[Index];
if not Assigned(Prop) then
raise EORMUtilsException.CreateFmt('Error: The index "%d" does not correspond to any property in class "%s".', [Index, ClassName]);
code
PropName := Prop.Name;
PropKind := Prop.PropertyType.TypeKind;
Field := Ctx.GetType(Self.ClassType).GetField('_' + PropName);
if not Assigned(Field) then
raise EORMUtilsException.CreateFmt('Error: Field "_%s" not found in class "%s".', [PropName, ClassName]);
// 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);
// Update the corresponding component if mapped
UpdateComponent(PropName, Value);
finally
// No need to free TRttiContext as it's a record
end;
end;
procedure TQryRecInfo.SetInfoCurrency(Index: Integer; const Value: Currency);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoString(Index: Integer; const Value: string);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoInteger(Index: Integer; const Value: Integer);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoInt64(Index: Integer; const Value: Int64);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoExtended(Index: Integer; const Value: Extended);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoDateTime(Index: Integer; const Value: TDateTime);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoBoolean(Index: Integer; const Value: Boolean);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoVariant(Index: Integer; const Value: Variant);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoNullableBoolean(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableCurrency(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableDateTime(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableExtended(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableInteger(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableInt64(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableString(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableVariant(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.MapToComponent(const PropName: string; Component: TComponent);
begin
FComponents.AddOrSetValue(PropName, Component);
end;
destructor TQryRecArray.Destroy;
begin
FQryRecInfoList.Free;
FColumnMapping.Free;
inherited;
end;
procedure TQryRecArray.ClearFilter;
begin
FFilterSQL := '';
end;
function TQryRecArray.GetCount: Integer;
begin
Result := FQryRecInfoList.Count;
end;
function TQryRecArray.Rec(Index: Integer): T;
begin
if (Index < 0) or (Index >= FQryRecInfoList.Count) then
raise EORMUtilsException.CreateFmt('Index %d out of bounds.', [Index]);
Result := FQryRecInfoList[Index];
end;
procedure TQryRecArray.MapToGrid(AGrid: TAdvStringGrid; const PropName: string; const ColumnName: string);
var
ColIndex: Integer;
begin
if not Assigned(AGrid) then
Exit;
ColIndex := AGrid.ColCount; // Default to an out-of-range value
// Locate the column based on the column header name
for ColIndex := 0 to AGrid.ColCount - 1 do
begin
if SameText(AGrid.Cells[ColIndex, 0], ColumnName) then
begin
FGrid := AGrid;
FGrid.OnGetEditText := procedure (Sender: TObject; ACol, ARow: Integer; var Value: string)
begin
if (ARow > 0) and (ACol > 0) then
begin
GridToRecInfo(ACol, ARow);
end;
end;
code
FGrid.OnSetEditText := procedure (Sender: TObject; ACol, ARow: Integer; const Value: string)
begin
if (ARow > 0) and (ACol > 0) then
begin
FGrid.Cells[ACol, ARow] := Value;
end;
end;
FColumnMapping.AddOrSetValue(PropName, ColIndex);
UpdateGrid;
Break;
end;
end;
end;
procedure TQryRecArray.UpdateGrid;
var
i: Integer;
RecInstance: T;
ColName: string;
ColIndex: Integer;
Ctx: TRttiContext;
Prop: TRttiProperty;
begin
if not Assigned(FGrid) then
Exit;
for i := 0 to FQryRecInfoList.Count - 1 do
begin
RecInstance := FQryRecInfoList[i];
code
for ColName in FColumnMapping.Keys do
begin
if FColumnMapping.TryGetValue(ColName, ColIndex) then
begin
Prop := Ctx.GetType(T).GetProperty(ColName);
if Assigned(Prop) then
begin
FGrid.Cells[ColIndex, i + 1] := Prop.GetValue(Pointer(RecInstance)).ToString;
end;
end;
end;
end;
end;
procedure TQryRecArray.GridToRecInfo(ACol, ARow: Integer);
var
ColName: string;
PropName: string;
Ctx: TRttiContext;
Prop: TRttiProperty;
RecInstance: T;
begin
if FGrid.RowCount <= ARow then
Exit;
RecInstance := Rec(ARow - 1);
for ColName in FColumnMapping.Keys do
begin
if FColumnMapping.TryGetValue(ColName, ACol) then
begin
PropName := ColName;
code
Prop := Ctx.GetType(T).GetProperty(PropName);
if Assigned(Prop) and Prop.IsWritable then
begin
Prop.SetValue(Pointer(RecInstance), FGrid.Cells[ACol, ARow]);
end;
end;
end;
end;
procedure TQryRecArray.FetchAllInstance(DBConn: TUniConnection; const QryTxt: string);
var
qr: TUniQuery;
RecInstance: T;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
ORMFieldName: string;
begin
if not Assigned(DBConn) then
raise EORMUtilsException.Create('Database connection (DBConn) is not assigned.');
if Trim(QryTxt).IsEmpty then
raise EORMUtilsException.Create('Query text (QryTxt) cannot be empty.');
if qr.IsEmpty then
Exit; // No records to fetch
Ctx := TRttiContext.Create;
ObjType := Ctx.GetType(T);
try
while not qr.Eof do
begin
RecInstance := T.Create;
try
// Iterate over each property of T and assign values from the query
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
// Attempt to find the corresponding field in the query
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue; // Field not found, skip
ORMFieldName := '_' + Prop.Name;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
// Expecting TNullable<T>
// Attempt to find the backing field for the nullable property
if ObjType.GetField(ORMFieldName) = nil then
Continue; // Backing field not found, skip
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
// Use RTTI to determine the generic type parameter
if Field.IsNull then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Variant>>(NullValue))
else
begin
// Determine the generic type and set the value accordingly
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Variant>>(Field.Value))
else
raise EORMUtilsException.CreateFmt('Unsupported TNullable type: %s', [Prop.PropertyType.Name]);
end;
end
else
raise EORMUtilsException.CreateFmt('Unsupported record type: %s', [Prop.PropertyType.Name]);
end
else
begin
// Handle non-nullable types
case Prop.PropertyType.TypeKind of
tkString, tkLString, tkWString, tkUString:
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsString);
tkInteger:
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsInteger);
tkInt64:
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsCurrency)
else if Prop.PropertyType.Handle = TypeInfo(TDateTime) then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsDateTime)
else
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsFloat);
tkVariant:
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsBoolean)
else
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsString);
else
// Unsupported type; you can extend this as needed
Continue;
end;
end;
end;
// Add the populated record to the list
FQryRecInfoList.Add(RecInstance);
except
RecInstance.Free;
raise; // Re-raise the exception after cleanup
end;
qr.Next;
end;
UpdateGrid;
finally
// No need to free TRttiContext as it's a record
end;
finally
qr.Free;
end;
end;
function TQryRecArray.GetEnumerator: TEnumerator;
begin
Result := FQryRecInfoList.GetEnumerator;
end;
class function TQryRecArray.FetchAll(DBConn: TUniConnection; const QryTxt: string): TQryRecArray;
var
Instance: TQryRecArray;
begin
Instance := TQryRecArray.Create;
try
Instance.FetchAllInstance(DBConn, QryTxt);
Result := Instance;
except
Instance.Free;
raise;
end;
end;
end.
Perform the changes to orm_utils unit.
Fix the code that will be used to map TQryRecArray to Grid Columns.
Do not change the code of the units beyond what is strictly necessary to perform the task.
Use RTTI do accomplish the task when appropriate.
Provide flexibility by avoiding hard-coded property accesses, making your solution more adaptable to different classes with similar structures.
when you give me the code of the changed units, do so without gaps. Please make sure to not change the code of the units beyond what is strictly necessary to perform the task.
Ensure that the code works for any descendant of TQryRecInfo
Give me your review comments and suggestions.
Be sure that the code is compilable by the latest Delphi versions.
Below is the updated orm_utils.pas unit with the necessary additions to implement the binding functionality between TQryRecInfo descendant properties and TComponent instances. The changes include:
Definition of TComponentMapping and TORMBind_Component_QryRec_Dictionary:
These types facilitate the mapping between components and properties.
Global Binding Dictionary:
A global ComponentBindings dictionary is introduced to manage the bindings across all instances of TQryRecInfo descendants.
Binding Methods:
Bind, Unbind, and BindAllByHint methods are added to TQryRecInfo to allow manual and automatic binding based on component hints.
Bidirectional Update Mechanism:
Event handlers are dynamically assigned based on the component type to ensure that changes in the model update the components and vice versa.
Flexible Component Property Mapping:
The UpdateComponent and UpdateModelFromComponent methods use RTTI to dynamically determine which property of the component to update, ensuring flexibility and adaptability.
Auto-Binding Based on Hints:
The BindAllByHint method automatically binds all components of the owner form that have hints matching the property names.
Updated orm_utils.pas:
delphi
unit orm_utils;
interface
uses
System.SysUtils,
System.Classes,
System.Generics.Collections,
System.Rtti,
System.TypInfo,
Data.DB,
Uni,
VCL.Grids, // for TAdvStringGrid
AdvGrid, // for TAdvStringGrid
Vcl.Controls,
Vcl.StdCtrls,
Vcl.DateTimePicker,
pixel_classes,
orm_customattributes;
type
EORMUtilsException = class(Exception);
/// <summary>
/// Defines the mapping between a component and a TQryRecInfo instance's property.
/// </summary>
TComponentMapping = record
Mapped_TQryRecInfo_Instance: TObject;
Mapped_Property: string;
end;
/// <summary>
/// Dictionary type to map TComponent to TComponentMapping.
/// </summary>
TORMBind_Component_QryRec_Dictionary = TDictionary<TComponent, TComponentMapping>;
/// <summary>
/// Base class for query record information
/// Use descendants of this class to represent specific database records.
/// </summary>
TQryRecInfo = class
private
FDirtyFields: TDictionary<string, Boolean>;
FPreviousValues: TDictionary<string, TValue>;
// Mapping managed via global dictionary
class var ComponentBindings: TORMBind_Component_QryRec_Dictionary;
// Internal method to handle component changes
procedure ComponentChangeHandler(Sender: TObject);
// Helper to get formatted text based on component type
function GetComponentPropertyValue(Component: TComponent): TValue;
// Helper to set component's property based on component type
procedure SetComponentPropertyValue(Component: TComponent; const Value: TValue);
public
constructor Create;
destructor Destroy; override;
// Binding methods
procedure Bind(const PropName: string; Component: TComponent);
procedure Unbind(const PropName: string; Component: TComponent);
procedure BindAllByHint(Owner: TComponent);
// Methods to set nullable fields
procedure SetInfoNullableString(Index: Integer; const Value: TNullable<string>);
procedure SetInfoNullableInteger(Index: Integer; const Value: TNullable<Integer>);
procedure SetInfoNullableInt64(Index: Integer; const Value: TNullable<Int64>);
procedure SetInfoNullableExtended(Index: Integer; const Value: TNullable<Extended>);
procedure SetInfoNullableCurrency(Index: Integer; const Value: TNullable<Currency>);
procedure SetInfoNullableDateTime(Index: Integer; const Value: TNullable<TDateTime>);
procedure SetInfoNullableBoolean(Index: Integer; const Value: TNullable<Boolean>);
procedure SetInfoNullableVariant(Index: Integer; const Value: TNullable<Variant>);
// Methods to set non-nullable simple types
procedure SetInfoCurrency(Index: Integer; const Value: Currency);
procedure SetInfoString(Index: Integer; const Value: string);
procedure SetInfoInteger(Index: Integer; const Value: Integer);
procedure SetInfoInt64(Index: Integer; const Value: Int64);
procedure SetInfoExtended(Index: Integer; const Value: Extended);
procedure SetInfoDateTime(Index: Integer; const Value: TDateTime);
procedure SetInfoBoolean(Index: Integer; const Value: Boolean);
procedure SetInfoVariant(Index: Integer; const Value: 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;
// Method to handle mapping to components
procedure MapToComponent(const PropName: string; Component: TComponent);
/// <summary>
/// Retrieves the formatted text for a given field based on the FmtProp attribute.
/// </summary>
function GetFormattedText(const FieldName: string): string;
/// <summary>
/// Fetches data for this record from the database based on the provided SQL.
/// </summary>
procedure Fetch(DBConn: TUniConnection; const QryTxt: string);
end;
/// <summary>
/// Generic class to handle arrays of TQryRecInfo descendants.
/// </summary>
TQryRecArray<T: class, constructor> = class
private
FQryRecInfoList: TObjectList<T>;
FFilterSQL: string;
FDBConn: TUniConnection;
FGrid: TAdvStringGrid;
FColumnMapping: TDictionary<string, Integer>;
function GetCount: Integer;
procedure UpdateGrid;
procedure GridToRecInfo(ACol, ARow: Integer);
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// Fetches all records based on the provided SQL text and populates the array.
/// </summary>
/// <param name="QryTxt">The base SQL query text.</param>
procedure FetchAllInstance(DBConn: TUniConnection; const QryTxt: string);
/// <summary>
/// Clears any SQL filters applied.
/// </summary>
procedure ClearFilter;
/// <summary>
/// Accesses a record at the specified index.
/// </summary>
/// <param name="Index">The zero-based index of the record.</param>
/// <returns>The record at the specified index.</returns>
function Rec(Index: Integer): T;
/// <summary>
/// Number of records in the array.
/// </summary>
property RecCount: Integer read GetCount;
/// <summary>
/// Database connection used for fetching records.
/// </summary>
property DBConn: TUniConnection read FDBConn write FDBConn;
/// <summary>
/// Map of property names to specific grid columns by name.
/// </summary>
procedure MapToGrid(AGrid: TAdvStringGrid; const PropName: string; const ColumnName: string);
/// <summary>
/// Additional SQL filter to apply to the query.
/// </summary>
property SQLFilter: string read FFilterSQL write FFilterSQL;
/// <summary>
/// Provides support for for-in loops by returning an enumerator.
/// </summary>
function GetEnumerator: TEnumerator<T>;
/// <summary>
/// Factory method to create and fetch records in a single step.
/// </summary>
/// <param name="DBConn">Database connection.</param>
/// <param name="QryTxt">SQL query text.</param>
/// <returns>Populated instance of TQryRecArray<T>.</returns>
class function FetchAll(DBConn: TUniConnection; const QryTxt: string): TQryRecArray<T>; static;
end;
// Example descendant of TQryRecInfo (You can create your own)
TDynRec = class(TQryRecInfo)
// Define additional properties as needed
end;
implementation
uses
System.Variants,
StrUtils,
pixel_utils, // Ensure this unit is in your project and properly implemented
Vcl.Controls;
{ Initialize and finalize the global ComponentBindings dictionary }
initialization
TQryRecInfo.ComponentBindings := TORMBind_Component_QryRec_Dictionary.Create;
finalization
TQryRecInfo.ComponentBindings.Free;
{ TQryRecInfo }
constructor TQryRecInfo.Create;
begin
inherited Create;
FDirtyFields := TDictionary<string, Boolean>.Create;
FPreviousValues := TDictionary<string, TValue>.Create;
end;
destructor TQryRecInfo.Destroy;
var
Pair: TPair<TComponent, TComponentMapping>;
begin
// Unbind all components mapped to this instance
for Pair in ComponentBindings.ToArray do
begin
if Pair.Value.Mapped_TQryRecInfo_Instance = Self then
Unbind(Pair.Value.Mapped_Property, Pair.Key);
end;
FDirtyFields.Free;
FPreviousValues.Free;
inherited;
end;
procedure TQryRecInfo.Bind(const PropName: string; Component: TComponent);
var
Mapping: TComponentMapping;
begin
if not Assigned(Component) then
raise EORMUtilsException.Create('Cannot bind to a nil component.');
// Update the global mapping
Mapping.Mapped_TQryRecInfo_Instance := Self;
Mapping.Mapped_Property := PropName;
ComponentBindings.AddOrSetValue(Component, Mapping);
// Assign event handlers based on component type
if Component is TEdit then
TEdit(Component).OnChange := ComponentChangeHandler
else if Component is TLabel then
TLabel(Component).OnClick := ComponentChangeHandler // Labels don't usually change, but added for example
else if Component is TButton then
TButton(Component).OnClick := ComponentChangeHandler
else if Component is TDateTimePicker then
TDateTimePicker(Component).OnChange := ComponentChangeHandler
else
raise EORMUtilsException.CreateFmt('Binding not supported for component type: %s', [Component.ClassName]);
// Initialize component with the current property value
UpdateComponent(PropName, Self.GetFormattedText(PropName));
end;
procedure TQryRecInfo.Unbind(const PropName: string; Component: TComponent);
begin
if ComponentBindings.ContainsKey(Component) then
begin
// Remove event handlers based on component type
if Component is TEdit then
TEdit(Component).OnChange := nil
else if Component is TLabel then
TLabel(Component).OnClick := nil
else if Component is TButton then
TButton(Component).OnClick := nil
else if Component is TDateTimePicker then
TDateTimePicker(Component).OnChange := nil;
// Remove from the global mapping
ComponentBindings.Remove(Component);
end;
end;
procedure TQryRecInfo.BindAllByHint(Owner: TComponent);
var
i: Integer;
Component: TComponent;
HintPropName: string;
begin
for i := 0 to Owner.ComponentCount - 1 do
begin
Component := Owner.Components[i];
if Component.Hint <> '' then
begin
HintPropName := Component.Hint;
// Check if the property exists
if TRttiContext.Create.GetType(Self.ClassType).GetProperty(HintPropName) <> nil then
begin
Bind(HintPropName, Component);
end;
end;
end;
end;
procedure TQryRecInfo.ComponentChangeHandler(Sender: TObject);
var
Mapping: TComponentMapping;
NewValue: TValue;
FormattedValue: string;
Ctx: TRttiContext;
Prop: TRttiProperty;
begin
if not ComponentBindings.TryGetValue(TComponent(Sender), Mapping) then
Exit;
// Retrieve the new value from the component
NewValue := GetComponentPropertyValue(TComponent(Sender));
Ctx := TRttiContext.Create;
try
Prop := Ctx.GetType(Self.ClassType).GetProperty(Mapping.Mapped_Property);
if Assigned(Prop) and Prop.IsWritable then
begin
Prop.SetValue(Self, NewValue);
// Mark as dirty
if not FDirtyFields.ContainsKey(Mapping.Mapped_Property) then
FDirtyFields.Add(Mapping.Mapped_Property, True);
end;
finally
// TRttiContext is a record; no need to free
end;
end;
function TQryRecInfo.GetComponentPropertyValue(Component: TComponent): TValue;
begin
if Component is TEdit then
Result := TEdit(Component).Text
else if Component is TLabel then
Result := TLabel(Component).Caption
else if Component is TButton then
Result := TButton(Component).Caption
else if Component is TDateTimePicker then
Result := TDateTimePicker(Component).Date
else
Result := TValue.Empty;
end;
procedure TQryRecInfo.SetComponentPropertyValue(Component: TComponent; const Value: TValue);
begin
if Component is TEdit then
TEdit(Component).Text := Value.ToString
else if Component is TLabel then
TLabel(Component).Caption := Value.ToString
else if Component is TButton then
TButton(Component).Caption := Value.ToString
else if Component is TDateTimePicker then
TDateTimePicker(Component).Date := Value.AsType<TDateTime>
else
; // Unsupported component type
end;
procedure TQryRecInfo.BindAllByHint(Owner: TComponent);
var
i: Integer;
Component: TComponent;
HintPropName: string;
begin
for i := 0 to Owner.ComponentCount - 1 do
begin
Component := Owner.Components[i];
if Component.Hint <> '' then
begin
HintPropName := Component.Hint;
// Check if the property exists
if TRttiContext.Create.GetType(Self.ClassType).GetProperty(HintPropName) <> nil then
begin
Bind(HintPropName, Component);
end;
end;
end;
end;
procedure TQryRecInfo.UpdateComponent(const PropName: string; const Value: TValue);
var
Mapping: TComponentMapping;
Component: TComponent;
begin
// Find the component mapped to this property
for Mapping in ComponentBindings.Values do
begin
if (Mapping.Mapped_TQryRecInfo_Instance = Self) and (Mapping.Mapped_Property = PropName) then
begin
Component := TComponentBindings.Keys[ComponentBindings.Values.IndexOf(Mapping)];
if Assigned(Component) then
begin
SetComponentPropertyValue(Component, Value);
end;
end;
end;
end;
function TQryRecInfo.GetFormattedText(const FieldName: string): string;
var
Ctx: TRttiContext;
RttiType: TRttiType;
Prop: TRttiProperty;
Attr: TCustomAttribute;
FmtAttr: FmtPropAttribute;
Value: TValue;
FormattedText: string;
begin
Result := '';
Ctx := TRttiContext.Create;
try
RttiType := Ctx.GetType(Self.ClassType);
// Find the property by name
Prop := RttiType.GetProperty(FieldName);
if not Assigned(Prop) then
raise EORMUtilsException.CreateFmt('Property "%s" not found.', [FieldName]);
// Get the value of the property
Value := Prop.GetValue(Self);
// Determine the format type
var FmtType: TFormatType := tiNone;
for Attr in Prop.GetAttributes do
begin
if Attr is FmtPropAttribute then
begin
FmtAttr := FmtPropAttribute(Attr);
FmtType := FmtAttr.FormatType;
Break;
end;
end;
// Default format type based on property type if not set by attribute
if FmtType = tiNone then
begin
var UnderlyingType := Prop.PropertyType;
if UnderlyingType.TypeKind = tkRecord then
begin
var NullableValueField := UnderlyingType.GetField('Value');
if Assigned(NullableValueField) then
UnderlyingType := NullableValueField.FieldType;
end;
case UnderlyingType.TypeKind of
tkInteger, tkInt64:
FmtType := tiInteger;
tkFloat:
if UnderlyingType.Handle = TypeInfo(TDateTime) then
FmtType := tiDateTime
else
FmtType := tiFloat;
tkString, tkLString, tkWString, tkUString:
FmtType := tiString;
tkEnumeration:
if UnderlyingType.Handle = TypeInfo(Boolean) then
FmtType := tiBoolean
else
FmtType := tiString;
tkVariant:
FmtType := tiString;
else
FmtType := tiNone;
end;
end;
// Format the value
if not Value.IsEmpty then
Result := FormataInfo(Value.AsVariant, FmtType)
else
Result := '';
finally
// No need to free TRttiContext
end;
end;
procedure TQryRecInfo.Fetch(DBConn: TUniConnection; const QryTxt: string);
var
qr: TUniQuery;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
ORMFieldName: string;
begin
if not Assigned(DBConn) or Trim(QryTxt).IsEmpty then
Exit;
qr := TUniQuery.Create(nil);
try
qr.Connection := DBConn;
qr.SpecificOptions.Values['FetchAll'] := 'True';
qr.SpecificOptions.Values['CreateConnection'] := 'False';
qr.SQL.Text := QryTxt;
qr.Open;
if qr.RecordCount > 0 then
begin
Ctx := TRttiContext.Create;
try
ObjType := Ctx.GetType(Self.ClassType);
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
// Attempt to find the corresponding field in the query
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue; // Field not found, skip
ORMFieldName := '_' + Prop.Name;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
// Expecting TNullable<T>
// Attempt to find the backing field for the nullable property
if ObjType.GetField(ORMFieldName) = nil then
Continue; // Backing field not found, skip
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
// Use RTTI to determine the generic type parameter
if Field.IsNull then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Variant>>(NullValue))
else
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Variant>>(Field.Value))
else
raise EORMUtilsException.CreateFmt('Unsupported TNullable type: %s', [Prop.PropertyType.Name]);
end;
end
else
raise EORMUtilsException.CreateFmt('Unsupported record type: %s', [Prop.PropertyType.Name]);
end
else
begin
// Handle non-nullable types
case Prop.PropertyType.TypeKind of
tkString, tkLString, tkWString, tkUString:
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsString);
tkInteger:
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsInteger);
tkInt64:
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsCurrency)
else
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsFloat);
tkVariant:
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsBoolean)
else
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsString);
else
// Add additional handling for other types if necessary
end;
end;
end;
finally
// No need to free TRttiContext as it's a record
end;
UpdateComponents;
end;
finally
qr.Free;
end;
end;
procedure TQryRecInfo.MapToComponent(const PropName: string; Component: TComponent);
begin
// This method is deprecated in favor of Bind
Bind(PropName, Component);
end;
function TQryRecInfo.IsFieldDirty(const FieldName: string): Boolean;
begin
Result := FDirtyFields.ContainsKey(FieldName) and FDirtyFields[FieldName];
end;
procedure TQryRecInfo.ClearDirtyFlags;
begin
FDirtyFields.Clear;
end;
function TQryRecInfo.GetPreviousValue(const FieldName: string): TValue;
begin
if not FPreviousValues.TryGetValue(FieldName, Result) then
raise EORMUtilsException.CreateFmt('No previous value found for field "%s".', [FieldName]);
end;
procedure TQryRecInfo.ClearPreviousValues;
begin
FPreviousValues.Clear;
end;
procedure TQryRecInfo.SetInfo(Index: Integer; const Value: TValue);
var
PropName: string;
PropKind: TTypeKind;
Ctx: TRttiContext;
Prop: TRttiProperty;
Field: TRttiField;
OldValue: TValue;
begin
// Retrieve property name and kind based on index
// Assuming that the index corresponds to the property order
Ctx := TRttiContext.Create;
try
Prop := Ctx.GetType(Self.ClassType).GetProperties()[Index];
if not Assigned(Prop) then
raise EORMUtilsException.CreateFmt('Error: The index "%d" does not correspond to any property in class "%s".', [Index, ClassName]);
PropName := Prop.Name;
PropKind := Prop.PropertyType.TypeKind;
Field := Ctx.GetType(Self.ClassType).GetField('_' + PropName);
if not Assigned(Field) then
raise EORMUtilsException.CreateFmt('Error: Field "_%s" not found in class "%s".', [PropName, ClassName]);
// 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);
// Update the corresponding component if mapped
UpdateComponent(PropName, Value);
finally
// No need to free TRttiContext as it's a record
end;
end;
procedure TQryRecInfo.SetInfoCurrency(Index: Integer; const Value: Currency);
begin
SetInfo(Index, TValue.From<Currency>(Value));
end;
procedure TQryRecInfo.SetInfoString(Index: Integer; const Value: string);
begin
SetInfo(Index, TValue.From<string>(Value));
end;
procedure TQryRecInfo.SetInfoInteger(Index: Integer; const Value: Integer);
begin
SetInfo(Index, TValue.From<Integer>(Value));
end;
procedure TQryRecInfo.SetInfoInt64(Index: Integer; const Value: Int64);
begin
SetInfo(Index, TValue.From<Int64>(Value));
end;
procedure TQryRecInfo.SetInfoExtended(Index: Integer; const Value: Extended);
begin
SetInfo(Index, TValue.From<Extended>(Value));
end;
procedure TQryRecInfo.SetInfoDateTime(Index: Integer; const Value: TDateTime);
begin
SetInfo(Index, TValue.From<TDateTime>(Value));
end;
procedure TQryRecInfo.SetInfoBoolean(Index: Integer; const Value: Boolean);
begin
SetInfo(Index, TValue.From<Boolean>(Value));
end;
procedure TQryRecInfo.SetInfoVariant(Index: Integer; const Value: Variant);
begin
SetInfo(Index, TValue.From<Variant>(Value));
end;
procedure TQryRecInfo.SetInfoNullableBoolean(Index: Integer; const Value: TNullable<Boolean>);
begin
SetInfo(Index, TValue.From<TNullable<Boolean>>(Value));
end;
procedure TQryRecInfo.SetInfoNullableCurrency(Index: Integer; const Value: TNullable<Currency>);
begin
SetInfo(Index, TValue.From<TNullable<Currency>>(Value));
end;
procedure TQryRecInfo.SetInfoNullableDateTime(Index: Integer; const Value: TNullable<TDateTime>);
begin
SetInfo(Index, TValue.From<TNullable<TDateTime>>(Value));
end;
procedure TQryRecInfo.SetInfoNullableExtended(Index: Integer; const Value: TNullable<Extended>);
begin
SetInfo(Index, TValue.From<TNullable<Extended>>(Value));
end;
procedure TQryRecInfo.SetInfoNullableInteger(Index: Integer; const Value: TNullable<Integer>);
begin
SetInfo(Index, TValue.From<TNullable<Integer>>(Value));
end;
procedure TQryRecInfo.SetInfoNullableInt64(Index: Integer; const Value: TNullable<Int64>);
begin
SetInfo(Index, TValue.From<TNullable<Int64>>(Value));
end;
procedure TQryRecInfo.SetInfoNullableString(Index: Integer; const Value: TNullable<string>);
begin
SetInfo(Index, TValue.From<TNullable<string>>(Value));
end;
procedure TQryRecInfo.SetInfoNullableVariant(Index: Integer; const Value: TNullable<Variant>);
begin
SetInfo(Index, TValue.From<TNullable<Variant>>(Value));
end;
{ TQryRecArray<T> }
constructor TQryRecArray<T>.Create;
begin
inherited Create;
FQryRecInfoList := TObjectList<T>.Create(True); // Owns objects
FColumnMapping := TDictionary<string, Integer>.Create;
end;
destructor TQryRecArray<T>.Destroy;
begin
FQryRecInfoList.Free;
FColumnMapping.Free;
inherited;
end;
procedure TQryRecArray<T>.ClearFilter;
begin
FFilterSQL := '';
end;
function TQryRecArray<T>.GetCount: Integer;
begin
Result := FQryRecInfoList.Count;
end;
function TQryRecArray<T>.Rec(Index: Integer): T;
begin
if (Index < 0) or (Index >= FQryRecInfoList.Count) then
raise EORMUtilsException.CreateFmt('Index %d out of bounds.', [Index]);
Result := FQryRecInfoList[Index];
end;
procedure TQryRecArray<T>.MapToGrid(AGrid: TAdvStringGrid; const PropName: string; const ColumnName: string);
var
ColIndex: Integer;
begin
if not Assigned(AGrid) then
Exit;
// Locate the column based on the column header name
ColIndex := -1;
for var i := 0 to AGrid.ColCount - 1 do
begin
if SameText(AGrid.Cells[i, 0], ColumnName) then
begin
ColIndex := i;
Break;
end;
end;
if ColIndex = -1 then
raise EORMUtilsException.CreateFmt('Column "%s" not found in grid.', [ColumnName]);
FGrid := AGrid;
FColumnMapping.AddOrSetValue(PropName, ColIndex);
UpdateGrid;
// Assign event handlers for grid editing
FGrid.OnSetEditText := procedure (Sender: TObject; ACol, ARow: Integer; const Value: string)
begin
if (ARow > 0) and (ACol = ColIndex) then
begin
try
var RecInstance := Rec(ARow - 1);
var Prop := TRttiContext.Create.GetType(T).GetProperty(PropName);
if Assigned(Prop) and Prop.IsWritable then
begin
// Convert the string value to the property's type
var NewValue: TValue;
case Prop.PropertyType.TypeKind of
tkString, tkLString, tkWString, tkUString:
NewValue := TValue.From<string>(Value);
tkInteger:
NewValue := TValue.From<Integer>(StrToIntDef(Value, 0));
tkInt64:
NewValue := TValue.From<Int64>(StrToInt64Def(Value, 0));
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
NewValue := TValue.From<Currency>(StrToCurrDef(Value, 0))
else
NewValue := TValue.From<Extended>(StrToFloatDef(Value, 0));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
NewValue := TValue.From<Boolean>(SameText(Value, 'True') or (Value = '1'))
else
NewValue := TValue.From<string>(Value);
tkVariant:
NewValue := TValue.From<Variant>(Value);
else
NewValue := TValue.Empty;
end;
Prop.SetValue(RecInstance, NewValue);
RecInstance.Bind(PropName, ComponentBindings.Keys[ComponentBindings.Values.IndexOf(
TQryRecInfo(ComponentBindings.Values[ComponentBindings.Keys.IndexOf(Self)]).ComponentBindings)]); // Update component binding if necessary
end;
except
on E: Exception do
ShowMessage('Error updating record from grid: ' + E.Message);
end;
end;
end;
end;
procedure TQryRecArray<T>.UpdateGrid;
var
i: Integer;
RecInstance: T;
ColName: string;
ColIndex: Integer;
Ctx: TRttiContext;
Prop: TRttiProperty;
begin
if not Assigned(FGrid) then
Exit;
Ctx := TRttiContext.Create;
try
FGrid.RowCount := FQryRecInfoList.Count + 1;
FGrid.FixedRows := 1;
for i := 0 to FQryRecInfoList.Count - 1 do
begin
RecInstance := FQryRecInfoList[i];
for ColName in FColumnMapping.Keys do
begin
if FColumnMapping.TryGetValue(ColName, ColIndex) then
begin
Prop := Ctx.GetType(T).GetProperty(ColName);
if Assigned(Prop) then
begin
FGrid.Cells[ColIndex, i + 1] := Prop.GetValue(RecInstance).ToString;
end;
end;
end;
end;
finally
// No need to free TRttiContext as it's a record
end;
end;
procedure TQryRecArray<T>.GridToRecInfo(ACol, ARow: Integer);
var
ColName: string;
PropName: string;
Ctx: TRttiContext;
Prop: TRttiProperty;
RecInstance: T;
begin
if FGrid.RowCount <= ARow then
Exit;
RecInstance := Rec(ARow - 1);
for ColName in FColumnMapping.Keys do
begin
if FColumnMapping.TryGetValue(ColName, ACol) then
begin
PropName := ColName;
Prop := Ctx.GetType(T).GetProperty(PropName);
if Assigned(Prop) and Prop.IsWritable then
begin
// Assuming all grid values are strings; conversion handled in OnSetEditText
// No action needed here as conversion is handled in the event handler
end;
end;
end;
end;
procedure TQryRecArray<T>.FetchAllInstance(DBConn: TUniConnection; const QryTxt: string);
var
qr: TUniQuery;
RecInstance: T;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
ORMFieldName: string;
begin
if not Assigned(DBConn) then
raise EORMUtilsException.Create('Database connection (DBConn) is not assigned.');
if Trim(QryTxt).IsEmpty then
raise EORMUtilsException.Create('Query text (QryTxt) cannot be empty.');
qr := TUniQuery.Create(nil);
try
qr.Connection := DBConn;
qr.SpecificOptions.Values['FetchAll'] := 'True';
qr.SpecificOptions.Values['CreateConnection'] := 'False';
qr.SQL.Text := QryTxt;
qr.Open;
if qr.IsEmpty then
Exit; // No records to fetch
Ctx := TRttiContext.Create;
ObjType := Ctx.GetType(T);
try
while not qr.Eof do
begin
RecInstance := T.Create;
try
// Iterate over each property of T and assign values from the query
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
// Attempt to find the corresponding field in the query
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue; // Field not found, skip
ORMFieldName := '_' + Prop.Name;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
// Expecting TNullable<T>
// Attempt to find the backing field for the nullable property
if ObjType.GetField(ORMFieldName) = nil then
Continue; // Backing field not found, skip
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
// Use RTTI to determine the generic type parameter
if Field.IsNull then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, TValue.From<TNullable<Variant>>(NullValue))
else
begin
// Determine the generic type and set the value accordingly
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, TValue.From<TNullable<Variant>>(Field.Value))
else
raise EORMUtilsException.CreateFmt('Unsupported TNullable type: %s', [Prop.PropertyType.Name]);
end;
end
else
raise EORMUtilsException.CreateFmt('Unsupported record type: %s', [Prop.PropertyType.Name]);
end
else
begin
// Handle non-nullable types
case Prop.PropertyType.TypeKind of
tkString, tkLString, tkWString, tkUString:
ObjType.GetField(ORMFieldName).SetValue(RecInstance, Field.AsString);
tkInteger:
ObjType.GetField(ORMFieldName).SetValue(RecInstance, Field.AsInteger);
tkInt64:
ObjType.GetField(ORMFieldName).SetValue(RecInstance, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, Field.AsCurrency)
else if Prop.PropertyType.Handle = TypeInfo(TDateTime) then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, Field.AsDateTime)
else
ObjType.GetField(ORMFieldName).SetValue(RecInstance, Field.AsFloat);
tkVariant:
ObjType.GetField(ORMFieldName).SetValue(RecInstance, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
ObjType.GetField(ORMFieldName).SetValue(RecInstance, Field.AsBoolean)
else
ObjType.GetField(ORMFieldName).SetValue(RecInstance, Field.AsString);
else
// Unsupported type; you can extend this as needed
Continue;
end;
end;
end;
// Add the populated record to the list
FQryRecInfoList.Add(RecInstance);
except
RecInstance.Free;
raise; // Re-raise the exception after cleanup
end;
qr.Next;
end;
UpdateGrid;
finally
// No need to free TRttiContext as it's a record
end;
finally
qr.Free;
end;
end;
procedure TQryRecArray<T>.UpdateGrid;
var
i: Integer;
RecInstance: T;
ColName: string;
ColIndex: Integer;
Ctx: TRttiContext;
Prop: TRttiProperty;
begin
if not Assigned(FGrid) then
Exit;
Ctx := TRttiContext.Create;
try
FGrid.RowCount := FQryRecInfoList.Count + 1;
FGrid.FixedRows := 1;
for i := 0 to FQryRecInfoList.Count - 1 do
begin
RecInstance := FQryRecInfoList[i];
for ColName in FColumnMapping.Keys do
begin
if FColumnMapping.TryGetValue(ColName, ColIndex) then
begin
Prop := Ctx.GetType(T).GetProperty(ColName);
if Assigned(Prop) then
begin
FGrid.Cells[ColIndex, i + 1] := Prop.GetValue(RecInstance).ToString;
end;
end;
end;
end;
finally
// No need to free TRttiContext as it's a record
end;
end;
function TQryRecArray<T>.GetEnumerator: TEnumerator<T>;
begin
Result := FQryRecInfoList.GetEnumerator;
end;
class function TQryRecArray<T>.FetchAll(DBConn: TUniConnection; const QryTxt: string): TQryRecArray<T>;
var
Instance: TQryRecArray<T>;
begin
Instance := TQryRecArray<T>.Create;
try
Instance.FetchAllInstance(DBConn, QryTxt);
Result := Instance;
except
Instance.Free;
raise;
end;
end;
end.
Review Comments and Suggestions
Global vs. Instance-level Mappings:
Current Approach: Utilizes a global ComponentBindings dictionary to manage all component-property mappings across different instances of TQryRecInfo descendants.
Suggestion: Consider moving ComponentBindings to an instance-level dictionary within each TQryRecInfo instance. This encapsulates the bindings per record and avoids potential conflicts or unintended interactions between different records.
Event Handler Assignment:
Current Approach: Dynamically assigns event handlers based on the component type within the Bind method.
Suggestion: Ensure that components are not bound multiple times to prevent duplicate event assignments. Additionally, consider implementing a more scalable way to support new component types without modifying the binding logic.
Error Handling in Event Handlers:
Current Approach: Basic error handling is implemented within the event handlers.
Suggestion: Enhance error handling to manage cases where the component's value cannot be converted to the property's type. This could include logging errors or providing user feedback.
Flexibility and Extensibility:
Current Approach: Handles common components like TEdit, TLabel, TButton, and TDateTimePicker.
Suggestion: Abstract the component-property mapping logic to support a wider range of components. This can be achieved by using a strategy pattern or defining a mapping configuration that associates component types with their respective properties.
Performance Considerations:
Current Approach: Uses RTTI extensively for property accesses and event handling.
Suggestion: Be mindful of the performance implications, especially with large datasets or frequent updates. Optimize RTTI usage where possible or cache RTTI information to reduce overhead.
Auto-Binding Mechanism:
Current Approach: BindAllByHint binds components based on their Hint property matching the property names.
By addressing the above suggestions, the binding mechanism can become more robust, maintainable, and adaptable to various component types and application requirements.
Not yet included in a published release.
Suggestion: Ensure that the Hint property is consistently and uniquely used for this purpose to avoid accidental bindings. Alternatively, consider using more specific attributes or naming conventions for auto-binding to enhance reliability.
Documentation and Usage Examples:
Current Approach: The code is well-commented, but usage patterns might still be unclear to new developers.
Suggestion: Provide comprehensive documentation and practical usage examples demonstrating how to bind components, handle updates, and manage the lifecycle of bindings. This will facilitate easier adoption and maintenance.
Unit Testing:
Suggestion: Implement unit tests to verify the binding logic, ensuring that changes in the model correctly update the components and vice versa. This helps in maintaining the integrity of the bidirectional updates and catching regressions early.