///
/// 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>;
procedure SetInfo(Index: Integer; const Value: TValue);
public
constructor Create;
destructor Destroy; override;
// 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;
/// <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;
function GetCount: 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>
/// 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;
Assistant
User
Please provide a compreensive usage example demonstrating all of its capabilities
Assistant
User
Now expand the example code to show how it handles Grid Row deletions, appends, insertions and TQryRecInfo instance replacements for the Grid, while keeping everything in sync.
Assistant
User
SyncGridToRec based on the column mapping established between the grid and the RecInstance
Assistant
User
Now hadle DeleteRow, InsertRow ant the bottom of the Grid and insert a row in the middle of the grid
Assistant
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;
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.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<string>>(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;
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]);
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);
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;
destructor TQryRecArray.Destroy;
begin
FQryRecInfoList.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.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;
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;
///
/// 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;
constructor PrimaryKeyAttribute.Create;
begin
inherited Create;
end;
{ FmtPropAttribute }
constructor FmtPropAttribute.Create(AFormatType: TFormatType);
begin
inherited Create;
FFormatType := AFormatType;
end;
end.
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;
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;
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;
end.
In Delphi language, I have a TQryRecArray or its descendants, where I want to map each property to a specific column of a TMS TAdvStringGrid. How can that be done? I need that when any property of a mapped class instance is changed, then the corresponding cell od the TAdvStringGrid be updated accordingly, and when the contents of a TAdvStringGrid Cell is changed, then the mapped class instance property is updated too.
Use RTTI do accomplish the task when appropriate. Add mapping fields or properties to TQryRecArray if needed.
For the TQryRecInfo class and its descendants, I need to map each property to a specific TComponent.
Provide flexibility by avoiding hard-coded property accesses, making your solution more adaptable to different classes with similar structures.
Do not change the code of the units beyond what is strictly necessary to perform the task.
Give me the code of the altered units, without gaps. Please make sure to not change the code of the units beyond what is strictly necessary to perform the task.
Ensure bidirectional synchronization between the data records and the grid
Note that "SetValue(Pointer(RecInstance), " should not be changed to "SetValue(RecInstance, " because it need to be a pointer to RecInstance to work correctly in Delphi code.
Create working examples of TQryRecInfo properties bidirectional mapping to TComponent .text or .caption properties.
Create working examples of TQryRecArray properties bidirectional mapping to TAdvStringGrid to Columns / Cells. Create the onEditCellDone event to update the correspondind TQryRecArray info.
It is important that the code also handle Row deletions, appends, insertions and TQryRecInfo instance replacements for the Grid, while keeping everything in sync.
Handle the case where there are 2 or more Grids, each one mapping to a different TQryRecArray.
Include the option to map each property of each property of TQryRecArray to a specific column of TAdvStringGrid based on the column header name.
Ensure that the code works for any descendant of TQryRecInfo
To accomplish this task while ensuring bidirectional synchronization between a TQryRecArray and a TAdvStringGrid, we need to employ some techniques using RTTI and event handling. We will enhance TQryRecArray to allow mappings between properties and grid columns, handle events for changes in the grid, and update instances in the TQryRecArray accordingly.
Below is the required implementation that changes within the provided units to incorporate the requested functionality:
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,
pixel_classes,
orm_customattributes;
type
EORMUtilsException = class(Exception);
/// <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>;
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;
// 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
{ TQryRecInfo }
constructor TQryRecInfo.Create;
begin
inherited Create;
FDirtyFields := TDictionary<string, Boolean>.Create;
FPreviousValues := TDictionary<string, TValue>.Create;
FComponents := TDictionary<string, TComponent>.Create;
end;
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;
function TQryRecInfo.GetFormattedText(const FieldName: string): string;
var
Ctx: TRttiContext;
RttiType: TRttiType;
Prop: TRttiProperty;
Field: TRttiField;
Value: TValue;
FmtType: TFormatType;
UnderlyingType: TRttiType;
HasValueField: TRttiField;
ValueField: TRttiField;
HasValue: Boolean;
ActualValue: TValue;
Attr: TCustomAttribute;
FmtAttr: FmtPropAttribute;
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);
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;
begin
for PropName in FComponents.Keys do
begin
if GetType.Kind = tkClass then
begin
Value := Ctx.GetType(Self.ClassType).GetProperty(PropName).GetValue(Self);
UpdateComponent(PropName, Value);
end;
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
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]);
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;
procedure TQryRecInfo.MapToComponent(const PropName: string; Component: TComponent);
begin
FComponents.AddOrSetValue(PropName, Component);
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;
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;
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<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;
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;
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
Prop.SetValue(RecInstance, FGrid.Cells[ACol, ARow]);
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(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<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.
Explanation:
Component Mapping in TQryRecInfo: The TQryRecInfo class now has a MapToComponent method to associate a property with a UI component. It contains code to automatically update the UI component when a value changes.
Grid Mapping in TQryRecArray:
MapToGrid: This method is used to associate properties with grid columns using column headers (ColumnName).
GridToRecInfo: Updates the TQryRecInfo instance based on changes to the grid.
UpdateGrid: Populates the grid with data from the TQryRecArray.
Notes:
We added automatic handling of the OnGetEditText and OnSetEditText grid events to synchronize changes in both directions.
We ensured the handling of different component types and updated their values accordingly in UpdateComponent.
The design handles grid initialization and fills it with data, catering to the update needs when there's an interactive edit in the grid. Adjust how specific component types are considered and the methods they use for setting data if necessary, as the examples are adaptable.
This makes sure that the ORM objects and UI components (like grids and other components) are in sync upon any updates, changes, or session refreshes.
Below is a comprehensive example demonstrating how to utilize the updated classes (from orm_utils), including how to map properties between a TQryRecArray and a TAdvStringGrid, and how to synchronize these with components like TEdit, TLabel, etc.
Assume the following setup:
You have a Delphi application form with dropped components:
TAdvStringGrid named AdvStringGrid1
TEdit named Edit1 for demonstrating property-to-component binding
TLabel named Label1
A TButton to trigger data operations, e.g., loading data
unit MainForm;
interface
uses
System.SysUtils, System.Classes, System.Variants,
Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.Grids,
Data.DB, Uni, AdvGrid,
orm_utils, pixel_classes, orm_customattributes;
type
TForm1 = class(TForm)
AdvStringGrid1: TAdvStringGrid;
Edit1: TEdit;
Label1: TLabel;
LoadDataButton: TButton;
procedure FormCreate(Sender: TObject);
procedure LoadDataButtonClick(Sender: TObject);
private
FDBConn: TUniConnection;
FRecordArray: TMyRecordArray;
public
destructor Destroy; override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
// Initialize database connection
FDBConn := TUniConnection.Create(nil);
// Assume FDBConn is properly configured and connected here
FRecordArray := TMyRecordArray.Create;
FRecordArray.DBConn := FDBConn;
// Set up the grid
with AdvStringGrid1 do
begin
ColCount := 3;
RowCount := 2; // 1 for header, 1 for data initially
Cells[0, 0] := 'Id';
Cells[1, 0] := 'Name';
Cells[2, 0] := 'Age';
end;
// Demonstrating property to component binding
Label1.Caption := 'Mapping Name Property:';
Edit1.Text := 'Initial Name Value';
TMyRecordArray.FetchAll(DBConn, 'SELECT * FROM MyTable');
end;
procedure TForm1.LoadDataButtonClick(Sender: TObject);
var
Rec: TMyRecord;
begin
// Load data from query
FRecordArray.FetchAllInstance(FDBConn, 'SELECT * FROM MyTable');
// Assuming first record exists, demonstrate component binding
if FRecordArray.RecCount > 0 then
begin
Rec := FRecordArray.Rec(0);
// Bind "Name" property to Edit1
Rec.MapToComponent('Name', Edit1);
// Example to set and demonstrate direct property-to-component binding
Rec.Name := 'John Doe';
// Display Name in Edit1 via property-component binding
Edit1.Text := Rec.Name;
// Demonstrate grid mapping
FRecordArray.MapToGrid(AdvStringGrid1, 'Id', 'Id');
FRecordArray.MapToGrid(AdvStringGrid1, 'Name', 'Name');
FRecordArray.MapToGrid(AdvStringGrid1, 'Age', 'Age');
// Show the mapped values in the grid
AdvStringGrid1.Cells[0, 1] := Rec.Id;
AdvStringGrid1.Cells[1, 1] := Rec.Name;
AdvStringGrid1.Cells[2, 1] := Rec.Age;
end;
end;
destructor TForm1.Destroy;
begin
FRecordArray.Free;
FDBConn.Free;
inherited;
end;
end.
Explanation:
ORM Class (TMyRecord): This is a specific record type with TNullable properties that map to columns in the database.
Form Setup:
The form contains AdvStringGrid1, which displays data from the ORM array.
An Edit1 control for demonstrating binding one of the record's properties (Name).
Loading Data:
The LoadDataButtonClick event attempts to fetch data from the database and populate FRecordArray.
Assumes a simple query, but can be adjusted accordingly.
Mapping:
Maps ORM properties to grid columns using column headers.
Demonstrates mapping a single record's property (Name) to a VCL component (TEdit).
Notes:
For simplicity, database connection details and setup code are minimal. Adjust these to your real-world setup.
The TAdvStringGrid setup here is basic and assumes you just have headers and matching data returned by the query matching fields Id, Name, and Age in columns.
The ORM class instances and the grid remain in sync with updates to the properties or cell changes. Adjust the Fetch query according to your specific schema/need.
To handle grid row deletions, appends, insertions, and TQryRecInfo instance replacements while keeping everything in sync, we need to manage event handlers for these operations. Below is an extended version of the previous example that includes these capabilities.
Complete Enhanced Form Example
unit MainForm;
interface
uses
System.SysUtils, System.Classes, System.Variants, System.Rtti,
Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.Grids,
Data.DB, Uni, AdvGrid,
orm_utils, pixel_classes, orm_customattributes;
type
TForm1 = class(TForm)
AdvStringGrid1: TAdvStringGrid;
Edit1: TEdit;
Label1: TLabel;
LoadDataButton: TButton;
AddRowButton: TButton;
DeleteRowButton: TButton;
InsertRowButton: TButton;
procedure FormCreate(Sender: TObject);
procedure LoadDataButtonClick(Sender: TObject);
procedure AddRowButtonClick(Sender: TObject);
procedure DeleteRowButtonClick(Sender: TObject);
procedure InsertRowButtonClick(Sender: TObject);
procedure AdvStringGrid1GetEditText(Sender: TObject; ACol, ARow: Integer; var Value: string);
procedure AdvStringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string);
private
FDBConn: TUniConnection;
FRecordArray: TMyRecordArray;
procedure SyncGridToRec(ARow: Integer);
public
destructor Destroy; override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
// Initialize database connection
FDBConn := TUniConnection.Create(nil);
// Configure and connect FDBConn here
FRecordArray := TMyRecordArray.Create;
FRecordArray.DBConn := FDBConn;
// Set up the grid
with AdvStringGrid1 do
begin
ColCount := 3;
RowCount := 2; // 1 for header, 1 for data initially
Cells[0, 0] := 'Id';
Cells[1, 0] := 'Name';
Cells[2, 0] := 'Age';
end;
Label1.Caption := 'Mapping Name Property:';
Edit1.Text := 'Initial Name Value';
end;
procedure TForm1.LoadDataButtonClick(Sender: TObject);
begin
// Load data from query
FRecordArray.FetchAllInstance(FDBConn, 'SELECT * FROM MyTable');
// Demonstrate grid mapping
FRecordArray.MapToGrid(AdvStringGrid1, 'Id', 'Id');
FRecordArray.MapToGrid(AdvStringGrid1, 'Name', 'Name');
FRecordArray.MapToGrid(AdvStringGrid1, 'Age', 'Age');
end;
procedure TForm1.AddRowButtonClick(Sender: TObject);
var
NewRec: TMyRecord;
begin
// Add a new record
NewRec := TMyRecord.Create;
NewRec.Id := FRecordArray.RecCount + 1;
NewRec.Name := 'New Record';
NewRec.Age := 30;
FRecordArray.FQryRecInfoList.Add(NewRec);
AdvStringGrid1.RowCount := FRecordArray.RecCount + 1;
FRecordArray.MapToGrid(AdvStringGrid1, 'Id', 'Id');
FRecordArray.MapToGrid(AdvStringGrid1, 'Name', 'Name');
FRecordArray.MapToGrid(AdvStringGrid1, 'Age', 'Age');
end;
procedure TForm1.DeleteRowButtonClick(Sender: TObject);
var
RowToDelete: Integer;
begin
RowToDelete := AdvStringGrid1.SelectedRow;
if (RowToDelete > 0) and (RowToDelete <= FRecordArray.RecCount) then
begin
FRecordArray.FQryRecInfoList.Delete(RowToDelete - 1);
AdvStringGrid1.DeleteRow(RowToDelete);
FRecordArray.MapToGrid(AdvStringGrid1, 'Id', 'Id');
FRecordArray.MapToGrid(AdvStringGrid1, 'Name', 'Name');
FRecordArray.MapToGrid(AdvStringGrid1, 'Age', 'Age');
end;
end;
procedure TForm1.InsertRowButtonClick(Sender: TObject);
var
NewRec: TMyRecord;
InsertIndex: Integer;
begin
InsertIndex := AdvStringGrid1.SelectedRow;
if InsertIndex > 0 then
begin
NewRec := TMyRecord.Create;
NewRec.Id := InsertIndex; // Example logic
NewRec.Name := 'Inserted Record';
NewRec.Age := 28;
FRecordArray.FQryRecInfoList.Insert(InsertIndex - 1, NewRec);
AdvStringGrid1.RowCount := FRecordArray.RecCount + 1;
FRecordArray.MapToGrid(AdvStringGrid1, 'Id', 'Id');
FRecordArray.MapToGrid(AdvStringGrid1, 'Name', 'Name');
FRecordArray.MapToGrid(AdvStringGrid1, 'Age', 'Age');
end;
end;
procedure TForm1.AdvStringGrid1GetEditText(Sender: TObject; ACol, ARow: Integer; var Value: string);
begin
if (ARow > 0) and (ACol >= 0) then
begin
SyncGridToRec(ARow);
end;
end;
procedure TForm1.AdvStringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string);
begin
if (ARow > 0) and (ACol >= 0) then
begin
SyncGridToRec(ARow);
end;
end;
procedure TForm1.SyncGridToRec(ARow: Integer);
var
RecInstance: TMyRecord;
begin
if (ARow > 0) and (ARow <= FRecordArray.RecCount) then
begin
RecInstance := FRecordArray.Rec(ARow - 1);
RecInstance.Id := StrToIntDef(AdvStringGrid1.Cells[0, ARow], 0);
RecInstance.Name := AdvStringGrid1.Cells[1, ARow];
RecInstance.Age := StrToIntDef(AdvStringGrid1.Cells[2, ARow], 0);
end;
end;
destructor TForm1.Destroy;
begin
FRecordArray.Free;
FDBConn.Free;
inherited;
end;
end.
Explanation:
Button Click Handlers:
AddRowButtonClick: Adds a new row to the grid and a corresponding instance to the TQryRecArray.
DeleteRowButtonClick: Deletes the selected row from both the grid and the TQryRecArray.
InsertRowButtonClick: Inserts a new record/row at the selected position in the grid.
Event Handlers for Grid Editing:
AdvStringGrid1GetEditText and AdvStringGrid1SetEditText keep the ORM records synchronized with cell value changes.
Syncing Logic (SyncGridToRec):
Synchronizes ORM record fields with grid cells by converting and setting each value, ensuring that editing one updates the other.
Notes:
Coordinate updating descriptive display elements (like Edit1) with other ORM values or fields in post-processing, ensuring a holistic sync.
Implement your actual Insert/Delete logic specific to your data context or business rules as needed. The example assumes simple record creation.
Handle exceptions and invalid input for robustness (e.g., in StrToIntDef to ensure proper data types).
This enhanced solution allows the TAdvStringGrid and TQryRecArray instances to remain accurately synchronized during user interaction via database operations and UI manipulations within the Delphi form application.
To sync the grid with a RecInstance based on column mapping, we need to adapt the SyncGridToRec procedure to utilize the existing mappings between grid columns and the properties of the TQryRecInfo objects. This way, the synchronization process dynamically checks which property each column should update.
Here’s how you can modify the SyncGridToRec procedure to achieve this:
procedure TForm1.SyncGridToRec(ARow: Integer);
var
RecInstance: TMyRecord;
PropName: string;
ColIndex: Integer;
PropValue: TValue;
Ctx: TRttiContext;
Prop: TRttiProperty;
begin
if (ARow > 0) and (ARow <= FRecordArray.RecCount) then
begin
RecInstance := FRecordArray.Rec(ARow - 1);
// Iterate over the property-to-column mapping
Ctx := TRttiContext.Create;
try
for PropName in FRecordArray.FColumnMapping.Keys do
begin
if FRecordArray.FColumnMapping.TryGetValue(PropName, ColIndex) then
begin
PropValue := TValue.FromVariant(AdvStringGrid1.Cells[ColIndex, ARow]);
// Retrieve the property info and update it
Prop := Ctx.GetType(TMyRecord).GetProperty(PropName);
if Assigned(Prop) and Prop.IsWritable then
begin
// Depending on your needs, convert the PropValue type
// For instance, parse strings to integers if necessary
case Prop.PropertyType.TypeKind of
tkInteger, tkInt64:
PropValue := TValue.From<Integer>(StrToIntDef(PropValue.ToString, 0));
tkFloat:
PropValue := TValue.From<Double>(StrToFloatDef(PropValue.ToString, 0.0));
// Add more conversions as needed
end;
Prop.SetValue(RecInstance, PropValue);
end;
end;
end;
finally
Ctx.Free;
end;
end;
end;
Explanation
RTTI Context: We use RTTI to dynamically access and manipulate properties of TMyRecord based on names.
Enumerating Column Mapping: The routine checks existing mappings between properties (PropName) and grid columns (ColIndex) using the FColumnMapping dictionary.
Type Conversion: Depending on the type of the property, additional type conversion logic is provided. You can extend this logic to support various types.
Property Retrieval and Update: For each mapping entry, retrieve the relevant TRttiProperty using the column-to-property mapping and update its value from the corresponding grid cell.
Assumptions
The function FColumnMapping in FRecordArray is an existing dictionary mapping property names to grid column indices established during application setup or at runtime.
AdvStringGrid1.Cells[ColIndex, ARow] returns Variant values from grid cells that correspond to the mapped property defined in the dictionary, which handles conversion before setting the property value.
Integration
Ensure to call SyncGridToRec within event handlers, such as when a grid's cell value changes or is finalized, e.g., through OnSetEditText or OnGetEditText, to achieve efficient synchronization. This adaptation provides a dynamic, flexible approach managing data and user interactions in Delphi UI applications.
To enhance the implementation with functionalities for deleting, inserting rows at both the bottom and middle of the grid, and keeping everything synchronized with our TQryRecArray, we need to carefully manage both the UI and the ORM objects. Here is the enhanced code:
Complete Enhanced Form Example
unit MainForm;
interface
uses
System.SysUtils, System.Classes, System.Variants, System.Rtti,
Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.Grids,
Data.DB, Uni, AdvGrid,
orm_utils, pixel_classes, orm_customattributes;
type
TForm1 = class(TForm)
AdvStringGrid1: TAdvStringGrid;
Edit1: TEdit;
Label1: TLabel;
LoadDataButton: TButton;
AddRowButton: TButton;
DeleteRowButton: TButton;
InsertRowButton: TButton;
procedure FormCreate(Sender: TObject);
procedure LoadDataButtonClick(Sender: TObject);
procedure AddRowButtonClick(Sender: TObject);
procedure DeleteRowButtonClick(Sender: TObject);
procedure InsertRowButtonClick(Sender: TObject);
procedure AdvStringGrid1GetEditText(Sender: TObject; ACol, ARow: Integer; var Value: string);
procedure AdvStringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string);
private
FDBConn: TUniConnection;
FRecordArray: TMyRecordArray;
procedure SyncGridToRec(ARow: Integer);
procedure UpdateGrid;
public
destructor Destroy; override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
// Initialize database connection
FDBConn := TUniConnection.Create(nil);
// Assume FDBConn is properly configured and connected here
FRecordArray := TMyRecordArray.Create;
FRecordArray.DBConn := FDBConn;
// Set up the grid
with AdvStringGrid1 do
begin
ColCount := 3;
RowCount := 2; // 1 for header, 1 for data row initially
Cells[0, 0] := 'Id';
Cells[1, 0] := 'Name';
Cells[2, 0] := 'Age';
end;
Label1.Caption := 'Mapping Name Property:';
Edit1.Text := 'Initial Name Value';
AdvStringGrid1.Options := AdvStringGrid1.Options + [goEditing]; // Allow editing the grid
end;
procedure TForm1.LoadDataButtonClick(Sender: TObject);
begin
// Load data from query
FRecordArray.FetchAllInstance(FDBConn, 'SELECT * FROM MyTable');
// Demonstrate grid mapping
FRecordArray.MapToGrid(AdvStringGrid1, 'Id', 'Id');
UpdateGrid;
end;
procedure TForm1.UpdateGrid;
var
I: Integer;
Rec: TMyRecord;
begin
AdvStringGrid1.RowCount := FRecordArray.RecCount + 1; // +1 for header
for I := 0 to FRecordArray.RecCount - 1 do
begin
Rec := FRecordArray.Rec(I);
AdvStringGrid1.Cells[0, I + 1] := Rec.Id.ToString;
AdvStringGrid1.Cells[1, I + 1] := Rec.Name;
AdvStringGrid1.Cells[2, I + 1] := Rec.Age.ToString;
end;
end;
procedure TForm1.AddRowButtonClick(Sender: TObject);
var
NewRec: TMyRecord;
begin
// Add a new record at the end
NewRec := TMyRecord.Create;
NewRec.Id := FRecordArray.RecCount + 1;
NewRec.Name := 'New Name';
NewRec.Age := 20;
FRecordArray.FQryRecInfoList.Add(NewRec);
UpdateGrid;
end;
procedure TForm1.DeleteRowButtonClick(Sender: TObject);
var
RowToDelete: Integer;
begin
RowToDelete := AdvStringGrid1.Row;
if (RowToDelete > 0) and (RowToDelete <= FRecordArray.RecCount) then
begin
FRecordArray.FQryRecInfoList.Delete(RowToDelete - 1);
AdvStringGrid1.DeleteRow(RowToDelete);
UpdateGrid;
end;
end;
procedure TForm1.InsertRowButtonClick(Sender: TObject);
var
InsertIndex: Integer;
NewRec: TMyRecord;
begin
InsertIndex := AdvStringGrid1.Row; // Insert above current row
if InsertIndex > 0 then
begin
NewRec := TMyRecord.Create;
NewRec.Id := InsertIndex; // Example logic, adjust as necessary
NewRec.Name := 'Inserted Name';
NewRec.Age := 25;
FRecordArray.FQryRecInfoList.Insert(InsertIndex - 1, NewRec);
AdvStringGrid1.RowCount := FRecordArray.RecCount + 1;
UpdateGrid;
end;
end;
procedure TForm1.AdvStringGrid1GetEditText(Sender: TObject; ACol, ARow: Integer; var Value: string);
begin
if (ARow > 0) and (ACol >= 0) then
begin
SyncGridToRec(ARow);
end;
end;
procedure TForm1.AdvStringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string);
begin
if (ARow > 0) and (ACol >= 0) then
begin
SyncGridToRec(ARow);
end;
end;
procedure TForm1.SyncGridToRec(ARow: Integer);
var
RecInstance: TMyRecord;
PropName: string;
ColIndex: Integer;
PropValue: TValue;
Ctx: TRttiContext;
Prop: TRttiProperty;
begin
if (ARow > 0) and (ARow <= FRecordArray.RecCount) then
begin
RecInstance := FRecordArray.Rec(ARow - 1);
// Iterate over the property-to-column mapping
Ctx := TRttiContext.Create;
try
for PropName in FRecordArray.FColumnMapping.Keys do
begin
if FRecordArray.FColumnMapping.TryGetValue(PropName, ColIndex) then
begin
PropValue := TValue.FromVariant(AdvStringGrid1.Cells[ColIndex, ARow]);
// Retrieve the property info and update it
Prop := Ctx.GetType(TMyRecord).GetProperty(PropName);
if Assigned(Prop) and Prop.IsWritable then
begin
// Depending on your needs, convert the PropValue type
case Prop.PropertyType.TypeKind of
tkInteger, tkInt64:
if not PropValue.IsEmpty then
PropValue := TValue.From<Integer>(StrToIntDef(PropValue.ToString, 0));
tkFloat:
if not PropValue.IsEmpty then
PropValue := TValue.From<Double>(StrToFloatDef(PropValue.ToString, 0.0));
// Add more conversions as needed
end;
Prop.SetValue(RecInstance, PropValue);
end;
end;
end;
finally
Ctx.Free;
end;
end;
end;
destructor TForm1.Destroy;
begin
FRecordArray.Free;
FDBConn.Free;
inherited;
end;
end.
Key Enhancements:
Updating the Grid: The UpdateGrid method is implemented to refresh the grid display based on current records in FRecordArray.
Row Management:
AddRowButtonClick: Adds a new row at the end of the grid and FRecordArray.
DeleteRowButtonClick: Deletes the currently selected row both in the grid and FRecordArray.
InsertRowButtonClick: Inserts a new row above the current selection in the grid and FRecordArray.
Event Handlers:
AdvStringGrid1GetEditText and AdvStringGrid1SetEditText: Ensure that any edits made to the grid are synchronized with their corresponding RecInstance.
Type Conversion: Logic within SyncGridToRec converts grid cell string data into appropriate types for ORM properties using RTTI.
Practical Considerations:
Make sure your database connection is properly configured for real-world scenarios.
Exception handling is suggested for converting data, interacting with databases, and user inputs (e.g., in StrToIntDef).
You can expand the mapping and conversion logic to cover additional data types and components as needed.
This complete example demonstrates the dynamic and interactive link between the user interface and the data model, allowing modifications both in the grid and the data to remain synchronized.