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<T>.Implicit(const AValue: T): TNullable<T>;
begin
  Result.Value := AValue;
  Result.HasValue := True;
end;

class operator TNullable<T>.Implicit(const AValue: TNullable<T>): T;
begin
  if AValue.HasValue then
    Result := AValue.Value
  else
    Result := Default(T); // or raise an exception
end;

class operator TNullable<T>.Implicit(const AValue: TNullValue): TNullable<T>;
begin
  Result.Value := Default(T);
  Result.HasValue := False;
end;

class operator TNullable<T>.Explicit(const AValue: T): TNullable<T>;
begin
  Result.Value := AValue;
  Result.HasValue := True;
end;

class operator TNullable<T>.Equal(const A: TNullable<T>; const B: TNullValue): Boolean;
begin
  Result := not A.HasValue;
end;

class operator TNullable<T>.NotEqual(const A: TNullable<T>; const B: TNullValue): Boolean;
begin
  Result := A.HasValue;
end;

end.

-----------------------

unit interposer_class;

interface

uses
  Vcl.Forms, Vcl.Controls, CommCtrl, Messages, sPanel, sEdit, sPageControl,
  System.Classes, AdvCGrid, Uni, pixel_classes;

{$TYPEINFO ON}

type
  TForm = class(Vcl.Forms.TForm)
  protected
    procedure CreateParams(var Params: TCreateParams); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  end;

  TsPanel = class(sPanel.TsPanel)
  protected
    procedure CreateParams(var Params: TCreateParams); override;
  end;

  TsEdit = class(sEdit.TsEdit)
  protected
    procedure CreateParams(var Params: TCreateParams); override;
  end;

  TsPageControl = class(sPageControl.TsPageControl)
  protected
    procedure CreateParams(var Params: TCreateParams); override;
  private
    procedure TCMAdjustRect(var Msg: TMessage); message TCM_ADJUSTRECT;
  end;

  TAdvColumnGrid = class(AdvCGrid.TAdvColumnGrid)
  private
    FByPassAF: TArray<Boolean>;
    FORMField: TArray<string>;

    function GetCells(ACol, ARow: Integer): TZString; // Getter for Cells
    procedure SetCells(ACol, ARow: Integer; const Value: TZString); // Setter for Cells
    function GetBypassAF(ACol: Integer): Boolean;
    procedure SetBypassAF(ACol: Integer; const Value: Boolean);
    function GetORMField(ACol: Integer): string; // Getter for ORMField
    procedure SetORMField(ACol: Integer; const Value: string); // Setter for ORMField
  protected
    procedure CreateParams(var Params: TCreateParams); override;
  public
    property Cells[ACol, ARow: Integer]: TZString read GetCells write SetCells; // Interposed property
    property BypassAutoFit[ACol: Integer]: Boolean read GetBypassAF write SetBypassAF;
    property ORMField[ACol: Integer]: string read GetORMField write SetORMField; // New ORMField property
  published
    function CriaLinhaObjeto(MyObject: TObject): Integer;
    function CriaLinha: Integer;
    function GetColumnIndexByName(const nome: string): Integer;
    procedure SetBasicColumnConfig;
  end;

implementation

uses
  pixel_utils, System.Math, System.Types, Windows, System.SysUtils, TypInfo,
  Generics.Collections, Data.DB, Vcl.Graphics, ComCtrls, Vcl.Grids;

procedure TForm.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  StrPCopy(Params.WinClassName, 'ZPro');
end;

constructor TForm.Create(AOwner: TComponent);
begin
  inherited;
end;

destructor TForm.Destroy;
begin
  inherited;
end;

procedure TsPanel.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  StrPCopy(Params.WinClassName, 'Painel');
end;

procedure TsEdit.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  StrPCopy(Params.WinClassName, 'Editor');
end;

procedure TsPageControl.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  StrPCopy(Params.WinClassName, 'PagCtrl');
end;

procedure TsPageControl.TCMAdjustRect(var Msg: TMessage);
begin
  inherited;
  case TabPosition of
    tpTop:
      begin
        PRect(Msg.LParam)^.Left := 0;
        PRect(Msg.LParam)^.Right := ClientWidth;
        PRect(Msg.LParam)^.Bottom := ClientHeight;
      end;
  end;
end;

procedure TAdvColumnGrid.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  StrPCopy(Params.WinClassName, 'Grid');
end;

function TAdvColumnGrid.GetCells(ACol, ARow: Integer): TZString;
begin
  Result := inherited Cells[ACol, ARow]; // Call the base class property
end;

procedure TAdvColumnGrid.SetCells(ACol, ARow: Integer; const Value: TZString);
begin
  inherited Cells[ACol, ARow] := string(Value); // Set the base class property
end;

function TAdvColumnGrid.GetBypassAF(ACol: Integer): Boolean;
begin
  Result := FByPassAF[ACol];
end;

procedure TAdvColumnGrid.SetBypassAF(ACol: Integer; const Value: Boolean);
begin
  if Length(FByPassAF) < ACol + 1 then
    SetLength(FByPassAF, ACol + 1);
  FByPassAF[ACol] := Value;
end;

function TAdvColumnGrid.GetORMField(ACol: Integer): string;
begin
  if Length(FORMField) > ACol then
    Result := FORMField[ACol]
  else
    Result := ''; // Return empty string if the column index is out of bounds
end;

procedure TAdvColumnGrid.SetORMField(ACol: Integer; const Value: string);
begin
  if Length(FORMField) < ACol + 1 then
    SetLength(FORMField, ACol + 1);
  FORMField[ACol] := Value; // Set the ORMField for the specific column
end;

function TAdvColumnGrid.CriaLinha: Integer;
begin
  Self.RowCount := Self.RowCount + 1;
  Self.ClearRows(Self.RowCount - 1, 1);
  Result := Self.RowCount - 1;
end;

function TAdvColumnGrid.CriaLinhaObjeto(MyObject: TObject): Integer;
begin
  Self.RowCount := Self.RowCount + 1;
  Self.ClearRows(Self.RowCount - 1, 1);
  Self.Objects[0, Self.RowCount - 1] := MyObject;
  Result := Self.RowCount - 1;
end;

function TAdvColumnGrid.GetColumnIndexByName(const nome: string): Integer;
begin
  Result := 0;
  for var i := 1 to Pred(Self.ColCount) do
    if Self.Columns[i].Name = nome then Exit(i);
end;

procedure TAdvColumnGrid.SetBasicColumnConfig;
var
  i: Integer;
begin
  with Self do
  begin
    SuppressColumn(0);
    for i := 1 to ColCount - 1 do
      if Columns[i].Tag = 0 then
      begin
        Columns[i].HeaderAlignment := taCenter;
        Columns[i].HeaderFont.Name := 'Tahoma';
        Columns[i].HeaderFont.Size := MulDiv(8, 96, Self.CurrentPPI);
        Columns[i].HeaderFont.Color := clWhite;
        Columns[i].HeaderFont.Style := [fsBold];
      end;
    for i := 1 to ColCount - 1 do
      if Columns[i].Tag = 0 then
      begin
        Columns[i].Font.Name := 'Verdana';
        Columns[i].Font.Size := MulDiv(10, 96, Self.CurrentPPI);
        Columns[i].Font.Style := [];
      end;
    for i := 1 to ColCount - 1 do
      if Columns[i].Tag = 0 then
      begin
        Columns[i].ShowBands := True;
        Colors[i, 0] := RGB($41, $3F, $42);
      end;

    for i := 1 to ColCount - 1 do
      Columns[i].Tag := 1; // Flag that default settings have been applied

    Bands.PrimaryColor := $00EFEFEF;
    Bands.SecondaryColor := $00F9F9F9;
    MouseActions.DirectEdit := True;
    MouseActions.DirectComboDrop := True;
    Bands.Active := True;
    ActiveCellShow := False;
    Navigation.SkipDisabledRows := True;
    Navigation.AutoComboSelect := False;
    ShowSelection := True;
    HideFocusRect := True;
    Options := Options - [goRangeSelect] + [goRowSelect];
    HoverRow := True;
    HoverRowColor := clYellow;
    ActiveRowShow := True;
    ActiveRowColor := clLime;
    SelectionColor := clLime;
    SelectionTextColor := clBlack;
    ColumnSize.Stretch := False;
    ColumnSize.StretchColumn := -1; // Sets the rightmost column to stretch
    ColumnSize.SynchWithGrid := False;
    FixedRowAlways := True;
    FixedRows := 1;
  end;
end;

end.

-----------------------

unit formgerenc_Classes;

{$TYPEINFO ON}

interface

uses
  orm_utils, pixel_classes, ORM_CustomAttributes;

type
  TEmployeeProject = class(TQryRecInfo)
  private
    [Table('employees'), PrimaryKey, RefColumn('emp_id')]
    _EmployeeID: TNullable<Integer>;
    [Table('employees'), PrimaryKey, RefColumn('dept_id')]
    _DepartmentID: TNullable<Integer>;
    [Table('employees'), RefColumn('emp_name')]
    _EmployeeName: TNullable<String>;
    [Table('projects'), PrimaryKey, RefColumn('proj_id')]
    _ProjectID: TNullable<Integer>;
    [Table('projects'), RefColumn('proj_name')]
    _ProjectName: TNullable<String>;
    [Table('projects'), RefColumn('proj_budget'), FmtProp(tiMoney)]
    _ProjectBudget: TNullable<Currency>;


    [FmtProp(tiMoney)]
    _BudgetLimit: Currency;

    _Age: Integer;
    _Older: Boolean;


    [Table('projects'), RefColumn('proj_date'), FmtProp(tiDate)]
    _ProjectDate: TNullable<TDateTime>;
    [Table('projects'), RefColumn('proj_starttime'), FmtProp(tiDateTime)]
    _ProjectStartMoment: TNullable<TDateTime>;

  published
    property EmployeeID: TNullable<Integer> index 0 read _EmployeeID write SetInfoNullableInteger;
    property DepartmentID: TNullable<Integer> index 1 read _DepartmentID write SetInfoNullableInteger;
    property EmployeeName: TNullable<String> index 2 read _EmployeeName write SetInfoNullableString;
    property ProjectID: TNullable<Integer> index 3 read _ProjectID write SetInfoNullableInteger;
    property ProjectName: TNullable<String> index 4 read _ProjectName write SetInfoNullableString;
    property ProjectBudget: TNullable<Currency> index 5 read _ProjectBudget write SetInfoNullableCurrency;
    property BudgetLimit: Currency index 6 read _BudgetLimit write SetInfoCurrency;
    property Age: Integer index 7 read _Age write SetInfoInteger;
    property Older: Boolean index 8 read _Older write SetInfoBoolean;
    property ProjectDate: TNullable<TDateTime> index 9 read _ProjectDate write SetInfoNullableDateTime;
    property ProjectStartMoment: TNullable<TDateTime> index 10 read _ProjectStartMoment write SetInfoNullableDateTime;
  end;

implementation

end.


-----------------------

unit orm_utils;

interface

uses
  System.SysUtils,
  System.Classes,
  System.Generics.Collections,
  System.Generics.Defaults,
  System.Rtti,
  System.TypInfo,
  Data.DB,
  Uni,
  pixel_classes,
  orm_customattributes,
  Vcl.Controls,
  Vcl.Forms,
  Dialogs,
  Variants;

type
  TQryRecInfo = class;

  // Define the event type
  TPropertyChangedEvent = procedure(Sender: TQryRecInfo; const PropertyName: string) of object;

  EORMUtilsException = class(Exception);

  /// <summary>
  /// Represents the key used in the component-ORM mapping dictionary.
  /// Combines a reference to an ORM record with a specific field name.
  /// </summary>
  TORMKey = record
    ORMRec: TQryRecInfo;
    FieldName: string;
  end;

  /// <summary>
  /// Custom comparer for TORMKey to handle equality checks and hashing.
  /// </summary>
  TORMKeyComparer = class(TEqualityComparer<TORMKey>)
    function Equals(const Left, Right: TORMKey): Boolean; override;
    function GetHashCode(const Key: TORMKey): Integer; override;
  end;

  /// <summary>
  /// Manages the binding between UI components and ORM records.
  /// </summary>
  TORMManager = class
  private
    FComponentDict: TDictionary<TORMKey, TComponent>;
  public
    constructor Create;
    destructor Destroy; override;

    /// <summary>
    /// Registers a component with its corresponding ORM record and field name.
    /// </summary>
    procedure RegisterComponent(Component: TComponent; ORMRec: TQryRecInfo; const FieldName: string);

    /// <summary>
    /// Unregisters a component from ORM binding.
    /// </summary>
    procedure UnregisterComponent(Component: TComponent);

    /// <summary>
    /// Finds the component associated with a specific ORM record and field name.
    /// </summary>
    function FindComponent(ORMRec: TQryRecInfo; const FieldName: string): TComponent;

    /// <summary>
    /// Retrieves all registered components.
    /// </summary>
    function GetAllComponents: TArray<TComponent>;

    /// <summary>
    /// Updates a component's UI based on the latest ORM record data.
    /// </summary>
    procedure UpdateComponentFromORM(Component: TComponent; ORMRec: TQryRecInfo; const FieldName: string);

    /// <summary>
    /// Retrieves the ORM record associated with a given component.
    /// </summary>
    function GetORMRecForComponent(Component: TComponent): TQryRecInfo;

    /// <summary>
    /// Retrieves the field name associated with a given component.
    /// </summary>
    function GetFieldNameForComponent(Component: TComponent): string;

    /// <summary>
    /// Registers components based on their Hint property.
    /// </summary>
    procedure RegisterComponentsByHint(MyForm: TForm; ORMRec: TQryRecInfo);
  end;

  /// <summary>
  /// Helper methods extending TComponent to interface with ORMManager.
  /// </summary>
  TComponentHelper = class helper for TComponent
  public
    /// <summary>
    /// Retrieves the ORM record associated with the component.
    /// </summary>
    function GetORMRec: TQryRecInfo;

    /// <summary>
    /// Retrieves the field name associated with the component.
    /// </summary>
    function GetORMRecField: string;
  end;

  /// <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>;
    FOnPropertyChanged: TPropertyChangedEvent; // New event
    FIsNewRec: Boolean; // New field

    procedure SetInfo(Index: Integer; const Value: TValue);
    // Other SetInfo overloads...

  public
    constructor Create;
    destructor Destroy; override;

    // Event property
    property OnPropertyChanged: TPropertyChangedEvent read FOnPropertyChanged write FOnPropertyChanged;

    // New property
    property IsNewRec: Boolean read FIsNewRec;

    // 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);

    /// <summary>
    /// Retrieves the value of a property by name.
    /// </summary>
    /// <param name="PropertyName">The name of the property to retrieve.</param>
    /// <returns>The value of the specified property as TValue.</returns>
    function GetPropertyValue(const PropertyName: string): TValue; // New method
  end;

  /// <summary>
  /// Generic class to handle arrays of TQryRecInfo descendants.
  /// </summary>
  TQryRecArray<T: TQryRecInfo, constructor> = class
  private
    FQryRecInfoList: TObjectList<T>;
    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;
  end;

// Declare ORMManager as a global variable in the interface for accessibility
var
  ORMManager: TORMManager;

implementation

uses
  pixel_utils,
  System.Math,
  System.Types,
  Windows,
  Vcl.StdCtrls,
  Vcl.WinXCtrls,
  Vcl.WinXPickers,
  StrUtils,
  DateUtils,
  System.Hash;

// =============================
// TORMKeyComparer Implementation
// =============================

function TORMKeyComparer.Equals(const Left, Right: TORMKey): Boolean;
begin
  Result := (Left.ORMRec = Right.ORMRec) and SameText(Left.FieldName, Right.FieldName);
end;

function TORMKeyComparer.GetHashCode(const Key: TORMKey): Integer;
begin
  Result := Integer(NativeUInt(Key.ORMRec)) xor THashBobJenkins.GetHashValue(LowerCase(Key.FieldName));
end;

// =============================
// TORMManager Implementation
// =============================

constructor TORMManager.Create;
begin
  inherited Create;
  FComponentDict := TDictionary<TORMKey, TComponent>.Create(TORMKeyComparer.Create);
end;

destructor TORMManager.Destroy;
begin
  FComponentDict.Free;
  inherited;
end;

procedure TORMManager.RegisterComponent(Component: TComponent; ORMRec: TQryRecInfo; const FieldName: string);
var
  Key: TORMKey;
begin
  Key.ORMRec := ORMRec;
  Key.FieldName := FieldName;

  if not FComponentDict.ContainsKey(Key) then
  begin
    FComponentDict.Add(Key, Component);
  end;
end;

procedure TORMManager.UnregisterComponent(Component: TComponent);
var
  Key: TORMKey;
  CopyKeys: TArray<TORMKey>;
  i: Integer;
begin
  // To safely remove components, first copy the keys
  CopyKeys := FComponentDict.Keys.ToArray;
  for i := 0 to Length(CopyKeys) - 1 do
  begin
    Key := CopyKeys[i];
    if FComponentDict[Key] = Component then
      FComponentDict.Remove(Key);
  end;
end;

function TORMManager.FindComponent(ORMRec: TQryRecInfo; const FieldName: string): TComponent;
var
  Key: TORMKey;
begin
  Key.ORMRec := ORMRec;
  Key.FieldName := FieldName;
  if FComponentDict.TryGetValue(Key, Result) then
    Exit
  else
    Result := nil;
end;

function TORMManager.GetAllComponents: TArray<TComponent>;
var
  Comp: TComponent;
  CompList: TList<TComponent>;
begin
  CompList := TList<TComponent>.Create;
  try
    for Comp in FComponentDict.Values do
      CompList.Add(Comp);
    Result := CompList.ToArray;
  finally
    CompList.Free;
  end;
end;

// Helper function to format information based on type
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;

procedure SetValueToComponent(aComponent: TComponent; TipoProp: TFormatType; Value: Variant);
begin
 if not Assigned(aComponent) then Exit;

 if TipoProp in [tiString, tiInteger, tiMoney, tiFloat, tiByteArray] then
 begin
  if IsPublishedProp(aComponent, 'Text') then SetPropValue(aComponent, 'Text', FormataInfo(Value, TipoProp))
  else if IsPublishedProp(aComponent, 'Caption') then SetPropValue(aComponent, 'Caption', FormataInfo(Value, TipoProp))
  else if IsPublishedProp(aComponent, 'Lines') then
  begin
   var Ctx: TRttiContext;
   Ctx:= TRttiContext.Create;
   var
   LineObjProp:= Ctx.GetType(aComponent.ClassType).GetProperty('Lines');
   var
   Strings_Obj:= TStrings(LineObjProp.GetValue(aComponent).AsObject);
   Strings_Obj.Text:= FormataInfo(Value, TipoProp);
   // LineObjProp.SetValue(aComponent, Strings_Obj);
  end;

 end
 else if TipoProp in [tiDate, tiDateTime] then
 begin
  if IsPublishedProp(aComponent, 'Date') then
  begin
   if (DateOf(Value) < EncodeDate(1900, 1, 1)) and (not IsPublishedProp(aComponent, 'Text')) then
   begin
    SetPropValue(aComponent, 'Date', DateOf(Now));
    var Ctx: TRttiContext;
    Ctx:= TRttiContext.Create;
    Ctx.GetType(aComponent.ClassType).GetMethod('Clear').Invoke(aComponent, []); // Limpa o campo Date
   end
   else SetPropValue(aComponent, 'Date', Value);
  end
  else if IsPublishedProp(aComponent, 'Text') then SetPropValue(aComponent, 'Text', FormataInfo(Value, TipoProp))
  else if IsPublishedProp(aComponent, 'Caption') then SetPropValue(aComponent, 'Caption', FormataInfo(Value, TipoProp));
 end
 else if TipoProp = tiBoolean then
 begin
  if IsPublishedProp(aComponent, 'Checked') then SetPropValue(aComponent, 'Checked', Boolean(Value))
  else if IsPublishedProp(aComponent, 'Text') then SetPropValue(aComponent, 'Text', FormataInfo(Value, TipoProp))
  else if IsPublishedProp(aComponent, 'Caption') then SetPropValue(aComponent, 'Caption', FormataInfo(Value, TipoProp));
 end
 else raise Exception.Create('SetValueToComponent: o Componente [' + aComponent.Name + ': ' + aComponent.ClassName + '] não está tratado');
end;

procedure TORMManager.UpdateComponentFromORM(Component: TComponent; ORMRec: TQryRecInfo; const FieldName: string);
var
  Ctx: TRttiContext;
  RttiType: TRttiType;
  Prop: TRttiProperty;
  Attr: TCustomAttribute;
  FmtAttr: FmtPropAttribute;
begin
  var ORMValue:= ORMRec.GetPropertyValue(FieldName).AsVariant;

  Ctx := TRttiContext.Create;

    RttiType := Ctx.GetType(ORMRec.ClassType);
    Prop := RttiType.GetProperty(FieldName);
    if not Assigned(Prop) then
      raise EORMUtilsException.CreateFmt('Property "%s" not found.', [FieldName]);

  var 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
      var 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
     var UnderlyingType := Prop.PropertyType;

      // Handle TNullable<T>
      if UnderlyingType.TypeKind = tkRecord then
      begin
        var 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;

  // showmessage(GetEnumName(TypeInfo(TFormatType), Integer(FmtType)));

  if not VarIsNull(ORMValue) then
   begin
    if IsPublishedProp(Component, 'Date') then
    begin
     if TDateTime(ORMValue) >= EncodeDate(1900, 1, 1) then SetValueToComponent(Component, FmtType, ORMValue)
     else SetValueToComponent(Component, FmtType, EncodeDate(1899, 01, 01));
    end
    else SetValueToComponent(Component, FmtType, ORMValue);
   end
   else
   begin
    SetValueToComponent(Component, FmtType, ORMValue.NullToDefault);
    if IsPublishedProp(Component, 'Date') then
    begin
     if IsPublishedProp(Component, 'Text') then
     begin
      var Ctx2: TRttiContext;
      Ctx2:= TRttiContext.Create;
      Ctx2.GetType(Component.ClassType).GetProperty('Text').SetValue(Pointer(Component), TValue.FromVariant('')); // Limpa o campo Text
     end
     else
     begin
      var Ctx2: TRttiContext;
      Ctx2:= TRttiContext.Create;
      Ctx2.GetType(Component.ClassType).GetMethod('Clear').Invoke(Component, []); // Limpa o campo Date
     end;
    end;
   end;
end;

function TORMManager.GetORMRecForComponent(Component: TComponent): TQryRecInfo;
var
  Key: TORMKey;
begin
  Result := nil;
  for Key in FComponentDict.Keys do
    if FComponentDict[Key] = Component then
    begin
      Result := Key.ORMRec;
      Exit;
    end;
end;

function TORMManager.GetFieldNameForComponent(Component: TComponent): string;
var
  Key: TORMKey;
begin
  Result := '';
  for Key in FComponentDict.Keys do
    if FComponentDict[Key] = Component then
    begin
      Result := Key.FieldName;
      Exit;
    end;
end;

procedure TORMManager.RegisterComponentsByHint(MyForm: TForm; ORMRec: TQryRecInfo);
var
  Context: TRttiContext;
  RttiType: TRttiType;
  RttiProperty: TRttiProperty;
  Component: TComponent;
  HintValue: TValue;
begin
  Context := TRttiContext.Create;
  try
    for Component in MyForm do
    begin
      RttiType := Context.GetType(Component.ClassType);
      RttiProperty := RttiType.GetProperty('Hint');

      if Assigned(RttiProperty) then
      begin
        HintValue := RttiProperty.GetValue(Component);
        if HintValue.IsEmpty then
          Continue;

        RttiType := Context.GetType(ORMRec.ClassType);
        for RttiProperty in RttiType.GetProperties do
        begin
          if (RttiProperty.Visibility = mvPublished) then
          begin
            if SameText(HintValue.AsString, RttiProperty.Name) then
            begin
              RegisterComponent(Component, ORMRec, RttiProperty.Name);
              Break;
            end;
          end;
        end;
      end;
    end;
  finally
    Context.Free;
  end;
end;

// =============================
// TComponentHelper Implementation
// =============================

function TComponentHelper.GetORMRec: TQryRecInfo;
begin
  Result := ORMManager.GetORMRecForComponent(Self);
end;

function TComponentHelper.GetORMRecField: string;
begin
  Result := ORMManager.GetFieldNameForComponent(Self);
end;

// =============================
// TQryRecInfo Implementation
// =============================

constructor TQryRecInfo.Create;
begin
  inherited Create;
  FDirtyFields := TDictionary<string, Boolean>.Create;
  FPreviousValues := TDictionary<string, TValue>.Create;
  FIsNewRec := False; // Initialize as not new
end;

destructor TQryRecInfo.Destroy;
begin
  FDirtyFields.Free;
  FPreviousValues.Free;
  inherited;
end;

procedure TQryRecInfo.ClearDirtyFlags;
begin
  FDirtyFields.Clear;
  FIsNewRec := False; // Reset IsNewRec when clearing dirty flags
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 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.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<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;

        // After fetching, reset dirty flags and IsNewRec
        ClearDirtyFlags;
      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);
      // Since a field is being modified, mark IsNewRec as true
      FIsNewRec := True;
    end;

    // Set the new value
    Field.SetValue(Self, Value);

    // Mark the property as dirty
    FDirtyFields.AddOrSetValue(PropName, True);

    // Trigger the OnPropertyChanged event
    if Assigned(FOnPropertyChanged) then
      FOnPropertyChanged(Self, PropName);

    // Update corresponding component if any
    var UpdatedComp := ORMManager.FindComponent(Self, PropName);
    if Assigned(UpdatedComp) then
      ORMManager.UpdateComponentFromORM(UpdatedComp, ORMManager.GetORMRecForComponent(UpdatedComp), ORMManager.GetFieldNameForComponent(UpdatedComp));

  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;

function TQryRecInfo.GetPropertyValue(const PropertyName: string): TValue;
var
  ctx: TRttiContext;
  rttiType: TRttiType;
  prop: TRttiProperty;
  UnderlyingType: TRttiType;
  Value: TValue;
  ValueField: TRttiField;
  HasValueField: TRttiField;
  HasValue: Boolean;
  ActualValue: TValue;
begin
  // Initialize the result
  Result := TValue.Empty;

  ctx := TRttiContext.Create;
  try
    rttiType := ctx.GetType(Self.ClassType);
    prop := rttiType.GetProperty(PropertyName);
    if not Assigned(prop) then
      raise EORMUtilsException.CreateFmt('Property "%s" not found in class "%s".', [PropertyName, Self.ClassName]);

    // Get the value of the property
    Value := prop.GetValue(Self);

    // Check if the property is a TNullable<T>
    if prop.PropertyType.TypeKind = tkRecord then
    begin
      // Assuming TNullable<T> has 'HasValue' and 'Value' fields
      ValueField := prop.PropertyType.GetField('Value');
      HasValueField := prop.PropertyType.GetField('HasValue');

      if Assigned(ValueField) and Assigned(HasValueField) then
      begin
        HasValue := HasValueField.GetValue(Value.GetReferenceToRawData).AsBoolean;
        if HasValue then
        begin
          ActualValue := ValueField.GetValue(Value.GetReferenceToRawData);
          Result := ActualValue;
        end
        else
        begin
          // Represent null value appropriately, e.g., using TValue.Empty or a custom indicator
          Result := TValue.Empty; // Or you can use a specific value or structure to indicate null
        end;
      end
      else
      begin
        // Not a TNullable<T>, return the value directly
        Result := Value;
      end;
    end
    else
    begin
      // Non-record types, return the value directly
      Result := Value;
    end;
  finally
    // TRttiContext is a record; no need to free
  end;
end;

// =============================
// TQryRecArray<T> Implementation
// =============================

constructor TQryRecArray<T>.Create;
begin
  inherited Create;
  FQryRecInfoList := TObjectList<T>.Create(True); // Owns objects
end;

destructor TQryRecArray<T>.Destroy;
begin
  FQryRecInfoList.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>.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<string>>(NullValue))
                else
                begin
                  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;

          // After setting properties, clear dirty flags and IsNewRec
          RecInstance.ClearDirtyFlags;

          // 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<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;

// =============================
// Initialization and Finalization
// =============================

initialization
  ORMManager := TORMManager.Create;

finalization
  ORMManager.Free;

end.

-----------------------

unit orm_binding;

interface

uses
  System.Classes, System.Rtti, System.Generics.Collections, orm_utils, AdvCGrid,
  Variants, SysUtils, StrUtils, pixel_classes, interposer_class;

type
  TORMBinding = class
  private
    FGrid: TAdvColumnGrid;
    FData: TQryRecArray<TQryRecInfo>;
    FColumnFields: TDictionary<Integer, string>; // Maps grid columns to property names
    FColumnTypes: TDictionary<Integer, TTypeKind>; // Maps grid columns to expected property types
    FRowMapping: TDictionary<Integer, TQryRecInfo>; // Maps grid rows to ORM records

    // Method to set ORM property based on field name and value
    procedure SetORMProperty(ORMRec: TQryRecInfo; const FieldName: string; const Value: TValue);
    procedure UpdateGridFromORM(ORMRec: TQryRecInfo; RowIndex: Integer); // Update grid cell based on ORM
  public
    constructor Create(AGrid: TAdvColumnGrid; AData: TQryRecArray<TQryRecInfo>);
    destructor Destroy; override;

    procedure SyncGridToData; // Sync grid changes to data
    procedure SyncDataToGrid; // Sync data changes to the grid
    procedure BindColumns;
    procedure UpdateGridCell(ACol: Integer; ARow: Integer); // Update a specific cell in the grid

    procedure GridCellChanged(Sender: TObject; ACol, ARow: Integer); // Event handler for cell changes
    procedure SetupCellBindings; // Setup event handlers and row mappings
  end;

implementation

{ TORMBinding }

constructor TORMBinding.Create(AGrid: TAdvColumnGrid; AData: TQryRecArray<TQryRecInfo>);
begin
  FGrid := AGrid;
  FData := AData;
  FColumnFields := TDictionary<Integer, string>.Create;
  FColumnTypes := TDictionary<Integer, TTypeKind>.Create; // Initialize the dictionary for types
  FRowMapping := TDictionary<Integer, TQryRecInfo>.Create; // Initialize row mapping
  BindColumns; // Set up column bindings
  SetupCellBindings; // Setup cell change event handlers
end;

destructor TORMBinding.Destroy;
begin
  FColumnFields.Free;
  FColumnTypes.Free; // Free the dictionary for types
  FRowMapping.Free; // Free the dictionary for row mapping
  inherited;
end;

procedure TORMBinding.BindColumns;
var
  i: Integer;
begin
  for i := 0 to FGrid.ColCount - 1 do
  begin
    // Check if the ORMField is not empty
    if FGrid.ORMField[i] <> '' then
    begin
      FColumnFields.Add(i, FGrid.ORMField[i]);

      // Example: Set expected property type for each column based on your ORM structure:
      case i of
        // Here you can add the actual expected mapping based on your ORM schema.
        // This is a placeholder
        0: FColumnTypes.Add(i, tkString);     // Example: Column 0 is a string
        1: FColumnTypes.Add(i, tkInteger);    // Example: Column 1 is an integer
        2: FColumnTypes.Add(i, tkFloat);      // Example: Column 2 is a float
        3: FColumnTypes.Add(i, tkEnumeration); // Example: Column 3 is a boolean
        // Add more mappings as necessary
      end;
    end;
  end;
end;

procedure TORMBinding.SetupCellBindings;
var
  i: Integer;
  ORMRec: TQryRecInfo;
begin
  // Map grid rows to ORM records and set Event handlers
  for i := 0 to FData.RecCount - 1 do
  begin
    ORMRec := FData.Rec(i);
    FRowMapping.Add(i, ORMRec); // Map row index to ORM instance
    SyncDataToGrid; // Initial sync to load data into the grid
  end;

  // Register the event for cell changes
  FGrid.OnEditCellDone := GridCellChanged;
end;

procedure TORMBinding.SyncGridToData;
var
  i, j: Integer;
  PropertyName: string;
  CellValue: TValue;
  ValueStr: string;
  PropertyType: TTypeKind;
begin
  for i := 0 to FData.RecCount - 1 do
  begin
    for j := 0 to FGrid.ColCount - 1 do
    begin
      if FColumnFields.TryGetValue(j, PropertyName) and FColumnTypes.TryGetValue(j, PropertyType) then
      begin
        ValueStr := FGrid.Cells[j, i];

        // Convert the string from the grid to the appropriate TValue based on the expected property type
        case PropertyType of
          tkString, tkLString, tkWString, tkUString:
            CellValue := TValue.From<string>(ValueStr);
          tkInteger:
            CellValue := TValue.From<Integer>(StrToInt(ValueStr));
          tkInt64:
            CellValue := TValue.From<Int64>(StrToInt64(ValueStr));
          tkFloat:
            CellValue := TValue.From<Extended>(StrToFloat(ValueStr));
          tkEnumeration: // Assuming boolean values
            CellValue := TValue.From<Boolean>(SameText(ValueStr, 'True'));
          else
            CellValue := TValue.Empty; // Handle unsupported types or empty values
        end;

        // Call SetORMProperty to update the ORM record with the new value
        SetORMProperty(FRowMapping[i], PropertyName, CellValue);
      end;
    end;
  end;
end;

procedure TORMBinding.SyncDataToGrid;
var
  i, j: Integer;
  PropertyName: string;
  PropertyType: TTypeKind;
  RecordInstance: TQryRecInfo;
begin
  for i := 0 to FData.RecCount - 1 do
  begin
    RecordInstance := FData.Rec(i);
    for j := 0 to FGrid.ColCount - 1 do
    begin
      if FColumnFields.TryGetValue(j, PropertyName) and FColumnTypes.TryGetValue(j, PropertyType) then
      begin
        // Get the property value from the record
        case PropertyType of
          tkString, tkLString, tkWString, tkUString:
            FGrid.Cells[j, i] := RecordInstance.GetPropertyValue(PropertyName).AsString;
          tkInteger:
            FGrid.Cells[j, i] := IntToStr(RecordInstance.GetPropertyValue(PropertyName).AsInteger);
          tkInt64:
            FGrid.Cells[j, i] := IntToStr(RecordInstance.GetPropertyValue(PropertyName).AsInt64);
          tkFloat:
            FGrid.Cells[j, i] := FloatToStr(RecordInstance.GetPropertyValue(PropertyName).AsExtended);
          tkEnumeration: // Assuming boolean values
            FGrid.Cells[j, i] := IfThen(RecordInstance.GetPropertyValue(PropertyName).AsBoolean, 'True', 'False');
          else
            FGrid.Cells[j, i] := ''; // Default to empty for unsupported types
        end;
      end;
    end;
  end;
end;

procedure TORMBinding.UpdateGridFromORM(ORMRec: TQryRecInfo; RowIndex: Integer);
var
  j: Integer;
  PropertyName: string;
  PropertyType: TTypeKind;
begin
  for j := 0 to FGrid.ColCount - 1 do
  begin
    if FColumnFields.TryGetValue(j, PropertyName) and FColumnTypes.TryGetValue(j, PropertyType) then
    begin
      // Populate grid from ORM record
      case PropertyType of
        tkString, tkLString, tkWString, tkUString:
          FGrid.Cells[j, RowIndex] := ORMRec.GetPropertyValue(PropertyName).AsString;
        tkInteger:
          FGrid.Cells[j, RowIndex] := IntToStr(ORMRec.GetPropertyValue(PropertyName).AsInteger);
        tkInt64:
          FGrid.Cells[j, RowIndex] := IntToStr(ORMRec.GetPropertyValue(PropertyName).AsInt64);
        tkFloat:
          FGrid.Cells[j, RowIndex] := FloatToStr(ORMRec.GetPropertyValue(PropertyName).AsExtended);
        tkEnumeration: // Assuming boolean values
          FGrid.Cells[j, RowIndex] := IfThen(ORMRec.GetPropertyValue(PropertyName).AsBoolean, 'True', 'False');
        else
          FGrid.Cells[j, RowIndex] := ''; // Default to empty for unsupported types
      end;
    end;
  end;
end;

procedure TORMBinding.UpdateGridCell(ACol: Integer; ARow: Integer);
begin
  // This method can trigger a data sync
  SyncGridToData; // Update ORM based on grid's content
end;

procedure TORMBinding.GridCellChanged(Sender: TObject; ACol, ARow: Integer);
begin
  // Update the corresponding ORM property based on the edited grid cell
  UpdateGridCell(ACol, ARow);
end;

procedure TORMBinding.SetORMProperty(ORMRec: TQryRecInfo; const FieldName: string; const Value: TValue);
var
  Ctx: TRttiContext;
  Prop: TRttiProperty;
  RowIndex: Integer;
begin
  Ctx := TRttiContext.Create;
  try
    Prop := Ctx.GetType(ORMRec.ClassType).GetProperty(FieldName);

    if Assigned(Prop) and Prop.IsWritable then
    begin
      // Set the property value
      Prop.SetValue(ORMRec, Value);

      // Instead of using IndexOf, we need to find the corresponding row index
      RowIndex := -1; // Initialize to an invalid index
      for var Key in FRowMapping.Keys do
      begin
        if FRowMapping[Key] = ORMRec then
        begin
          RowIndex := Key; // Found the row index
          Break; // Exit the loop once we find the match
        end;
      end;

      if RowIndex <> -1 then
        UpdateGridFromORM(ORMRec, RowIndex); // Update grid cell based on ORM changes
    end
    else
      raise Exception.CreateFmt('Property "%s" not found or not writable in record "%s".', [FieldName, ORMRec.ClassName]);
  finally
    // TRttiContext is a record and managed automatically
  end;
end;

end.

-----------------------

In the supplied code, I want to map a TQryRecArray instance to a specific TAdvColumnGrid (which is a descendant of TStringGrid). How can that be done? I need that when any property of a mapped class instance is changed, then the corresponding cell od the TStringGrid be updated accordingly, and when the contents of a TStringGrid Cell is changed, then the mapped class instance property is updated too.
Use ORMField to know witch TQryRecInfo property is to be used to each column
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.
Create a Dictionary to bind each Grid Row to its respective TQryRecInfo of TQryRecArray

In the Form we use this event to sgnal a Grid Cell change:
procedure TMainForm.GridNomesEditCellDone(Sender: TObject; ACol, ARow: Integer);

Base on the above information, Please review and fix unit orm_binding, including a procedure to populate and maps a TAdvColumnGrid with the contents of a TQryRecArray