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>);
procedure SetInfoCurrency(Index: Integer; const Value: Currency);
// 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;
procedure Fetch(DBConn: TUniConnection; const QryTxt: string);
/// <summary>
/// Class method to fetch multiple records from a query and return a list of TQryRecInfo instances.
/// </summary>
class function FetchAll(DBConn: TUniConnection; const QryTxt: string): TObjectList<TQryRecInfo>;
end;
function FormataInfo(info: Variant; tipo: TFormatType): string;
type
TDynRec = class(TQryRecInfo)
end;
implementation
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;
NullableFieldName: string;
begin
if not Assigned(DBConn) or Trim(QryTxt).IsEmpty then
Exit;
if qr.RecordCount > 0 then
begin
Ctx := TRttiContext.Create;
try
// Corrected: Directly pass the class reference without using ClassType
ObjType := Ctx.GetType(TQryRecInfo);
qr.First;
while not qr.Eof do
begin
RecInfo := TQryRecInfo.Create;
try
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
NullableFieldName := '_' + Prop.Name;
if ObjType.GetField(NullableFieldName) = nil then
Continue;
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
// Use implicit operators to assign value directly
if Field.IsNull then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(NullValue))
else
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(Field.AsString));
// Extend handling for other types as needed
// Example:
// if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
// ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(Field.AsInteger))
// Add similar clauses for other nullable types
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:
Prop.SetValue(RecInfo, Field.AsString);
tkInteger:
Prop.SetValue(RecInfo, Field.AsInteger);
tkInt64:
Prop.SetValue(RecInfo, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
Prop.SetValue(RecInfo, Field.AsCurrency)
else
Prop.SetValue(RecInfo, Field.AsFloat);
tkVariant:
Prop.SetValue(RecInfo, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
Prop.SetValue(RecInfo, 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;
Result.Add(RecInfo);
except
RecInfo.Free;
raise;
end;
qr.Next;
end;
finally
// No need to free TRttiContext as it's a record
end;
end;
finally
qr.Free;
end;
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.IsFieldDirty(const FieldName: string): Boolean;
begin
Result := FDirtyFields.ContainsKey(FieldName);
end;
procedure TQryRecInfo.ClearDirtyFlags;
begin
FDirtyFields.Clear;
end;
procedure TQryRecInfo.ClearPreviousValues;
begin
FPreviousValues.Clear;
end;
procedure TQryRecInfo.SetInfo(Index: Integer; const Value: TValue);
var
PropName: string;
PropKind: TTypeKind;
Ctx: TRttiContext;
Prop: TRttiProperty;
Field: TRttiField;
OldValue: TValue;
begin
// Retrieve property name and kind based on index
// Assuming that the index corresponds to the property order
Ctx := TRttiContext.Create;
try
Prop := Ctx.GetType(Self.ClassType).GetProperties()[Index];
if not Assigned(Prop) then
raise EORMUtilsException.CreateFmt('Error: The index "%d" does not correspond to any property in class "%s".', [Index, ClassName]);
code
PropName := Prop.Name;
PropKind := Prop.PropertyType.TypeKind;
Field := Ctx.GetType(Self.ClassType).GetField('_' + PropName);
if not Assigned(Field) then
raise EORMUtilsException.CreateFmt('Error: Field "_%s" not found in class "%s".', [PropName, ClassName]);
// If the field is not yet dirty, store the previous value
if not FDirtyFields.ContainsKey(PropName) then
begin
OldValue := Field.GetValue(Self);
FPreviousValues.AddOrSetValue(PropName, OldValue);
end;
// Set the new value
Field.SetValue(Self, Value);
// Mark the property as dirty
FDirtyFields.AddOrSetValue(PropName, True);
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.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;
end.
The code snippet below only works when Field is Null. Fix the code so it works for the other TNullable
code
if Field.IsNull then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<string>>(NullValue))
Assistant
The issue in the code is that it only handles the case where the Field is null for the TNullable<string> type, and doesn't correctly handle setting values for other TNullable<T> types when the Field is not null. To fix this, we need to extend the Fetch method logic to handle all TNullable<T> types, both when Field is null and when it contains a valid value.
Here is how you can modify the Fetch method to handle other TNullable types:
Add logic to determine and correctly assign values to fields of type TNullable<T>.
pascal
User
Fix the TQryRecInfo.FetchAll the same way you did on the TQryRecInfo.Fetch
Create a concrete usage example of TQryRecInfo.FetchAll
Assistant
To extend the TQryRecInfo.FetchAll method in the same way as we did for the TQryRecInfo.Fetch, we will implement similar logic to correctly handle each TNullable<T> type. This involves checking whether the field is null and then setting the appropriate TNullable<T> value.
Here's the updated TQryRecInfo.FetchAll method:
pascal
User
change FetchAll so it uses Generics so we can use descendants of TQryRecInfo
Assistant
To enable the FetchAll method to handle any descendants of TQryRecInfo, we can use generics to create a more flexible implementation. This requires the method to accept a class type parameter and instantiate the objects accordingly.
Here's how you can modify the FetchAll method to use generics:
pascal
User
the code below is giving a compiler error: ',', ';' or '>' expected but ':' found
class function TQryRecInfo.FetchAll<T: TQryRecInfo, constructor>(DBConn: TUniConnection; const QryTxt: string): TObjectList;
Review the code and fix it
Assistant
The compiler error you're encountering usually indicates a syntax issue with the generic constraints. In Delphi, when defining constraints for generic types, the correct format is to separate multiple constraints with a space, not a comma. Additionally, ensure that all the relevant constraints are correctly ordered and specified.
Let's correct the syntax and provide the modified method signature:
pascal
class function TQryRecInfo.FetchAll<T: TQryRecInfo, constructor>(DBConn: TUniConnection; const QryTxt: string): TObjectList<T>;
You should use the following structure without a comma between the class type and constructor constraint:
pascal
class function TQryRecInfo.FetchAll<T: TQryRecInfo, constructor>(DBConn: TUniConnection; const QryTxt: string): TObjectList<T>;
Here's the updated code with the correct generics constraint:
pascal
User
is is still not compiling
Assistant
I apologize for the confusion earlier. Let's address the generic method syntax error specifically for Delphi. The use of generics in Delphi requires careful attention to syntax, especially in the constraints section.
Here is the corrected generic function signature and implementation:
pascal
User
class function TQryRecInfo.FetchAll<T: TQryRecInfo>(DBConn: TUniConnection; const QryTxt: string): TObjectList;
[dcc32 Error] orm_utils.pas(395): E2029 ',', ';' or '>' expected but ':' found
Assistant
The error you're seeing is because Delphi expects the constructor constraint to be explicitly stated when you use T.Create to instantiate objects. You need to explicitly declare the constructor constraint.
In Delphi, the correct way to specify constraints for generics is to separate them with spaces and not use commas. Here's the correct syntax:
pascal
class function TQryRecInfo.FetchAll<T: TQryRecInfo, constructor>(DBConn: TUniConnection; const QryTxt: string): TObjectList<T>;
Let's ensure the entire function uses this corrected signature:
pascal
Not yet included in a published release.
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;
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
NullableFieldName := '_' + Prop.Name;
if ObjType.GetField(NullableFieldName) = nil then
Continue;
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
// Use implicit operators to assign value directly
if Field.IsNull then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<string>>(NullValue))
else
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Variant>>(Field.Value));
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:
Prop.SetValue(Self, Field.AsString);
tkInteger:
Prop.SetValue(Self, Field.AsInteger);
tkInt64:
Prop.SetValue(Self, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
Prop.SetValue(Self, Field.AsCurrency)
else
Prop.SetValue(Self, Field.AsFloat);
tkVariant:
Prop.SetValue(Self, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
Prop.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;
procedure TQryRecInfo.Fetch(DBConn: TUniConnection; const QryTxt: string);
var
qr: TUniQuery;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
NullableFieldName: 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;
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
NullableFieldName := '_' + Prop.Name;
if ObjType.GetField(NullableFieldName) = nil then
Continue;
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
// Determine underlying type
if Field.IsNull then
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<string>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Integer>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Int64>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Extended>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Currency>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<TDateTime>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Boolean>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Variant>>(NullValue));
end
else
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(Self, TValue.From<TNullable<Variant>>(Field.Value));
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:
Prop.SetValue(Self, Field.AsString);
tkInteger:
Prop.SetValue(Self, Field.AsInteger);
tkInt64:
Prop.SetValue(Self, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
Prop.SetValue(Self, Field.AsCurrency)
else
Prop.SetValue(Self, Field.AsFloat);
tkVariant:
Prop.SetValue(Self, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
Prop.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;
In this updated code, we handle each possible TNullable<T> type by checking both when the field is Null and when it contains a value. For each type, we use the corresponding method from TValue to set it correctly. This ensures that all TNullable<T> types are handled properly in the Fetch method.
class function TQryRecInfo.FetchAll(DBConn: TUniConnection; const QryTxt: string): TObjectList<TQryRecInfo>;
var
qr: TUniQuery;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
NullableFieldName: string;
RecInfo: TQryRecInfo;
begin
Result := TObjectList<TQryRecInfo>.Create(True); // Owns objects
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(TQryRecInfo);
qr.First;
while not qr.Eof do
begin
RecInfo := TQryRecInfo.Create;
try
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
NullableFieldName := '_' + Prop.Name;
if ObjType.GetField(NullableFieldName) = nil then
Continue;
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
if Field.IsNull then
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Variant>>(NullValue));
end
else
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Variant>>(Field.Value));
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:
Prop.SetValue(RecInfo, Field.AsString);
tkInteger:
Prop.SetValue(RecInfo, Field.AsInteger);
tkInt64:
Prop.SetValue(RecInfo, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
Prop.SetValue(RecInfo, Field.AsCurrency)
else
Prop.SetValue(RecInfo, Field.AsFloat);
tkVariant:
Prop.SetValue(RecInfo, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
Prop.SetValue(RecInfo, 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;
Result.Add(RecInfo);
except
RecInfo.Free;
raise;
end;
qr.Next;
end;
finally
// No need to free TRttiContext as it's a record
end;
end;
finally
qr.Free;
end;
end;
Usage Example
Suppose you have a database table named Users with fields ID, Name, and Age, and you want to fetch all users into a list of TQryRecInfo objects.
Example Code
pascal
procedure RetrieveUsers(DBConn: TUniConnection);
const
UserQuery = 'SELECT ID, Name, Age FROM Users';
var
UsersList: TObjectList<TQryRecInfo>;
User: TQryRecInfo;
begin
// Fetch all users from the database
UsersList := TQryRecInfo.FetchAll(DBConn, UserQuery);
try
for User in UsersList do
begin
// Assuming that the TQryRecInfo class has properties ID, Name, and Age
Writeln('User ID: ', User.GetFormattedText('ID'));
Writeln('Name: ', User.GetFormattedText('Name'));
Writeln('Age: ', User.GetFormattedText('Age'));
Writeln('---');
end;
finally
UsersList.Free;
end;
end;
In this usage example, we use the FetchAll method to retrieve all users from the Users table and then print out the formatted values for ID, Name, and Age using the GetFormattedText method. Note that TQryRecInfo should be populated with corresponding properties in your actual implementation to match the fields in the table being queried.
class function TQryRecInfo.FetchAll<T: TQryRecInfo, constructor>(DBConn: TUniConnection; const QryTxt: string): TObjectList<T>;
var
qr: TUniQuery;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
NullableFieldName: string;
RecInfo: T;
begin
Result := TObjectList<T>.Create(True); // Owns objects
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(T);
qr.First;
while not qr.Eof do
begin
RecInfo := T.Create;
try
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
NullableFieldName := '_' + Prop.Name;
if ObjType.GetField(NullableFieldName) = nil then
Continue;
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
if Field.IsNull then
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Variant>>(NullValue));
end
else
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Variant>>(Field.Value));
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:
Prop.SetValue(RecInfo, Field.AsString);
tkInteger:
Prop.SetValue(RecInfo, Field.AsInteger);
tkInt64:
Prop.SetValue(RecInfo, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
Prop.SetValue(RecInfo, Field.AsCurrency)
else
Prop.SetValue(RecInfo, Field.AsFloat);
tkVariant:
Prop.SetValue(RecInfo, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
Prop.SetValue(RecInfo, 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;
Result.Add(RecInfo);
except
RecInfo.Free;
raise;
end;
qr.Next;
end;
finally
// No need to free TRttiContext as it's a record
end;
end;
finally
qr.Free;
end;
end;
Here's how you can use FetchAll with the TUserInfo descendant:
pascal
procedure RetrieveUsers(DBConn: TUniConnection);
const
UserQuery = 'SELECT ID, Name, Age FROM Users';
var
UsersList: TObjectList<TUserInfo>;
User: TUserInfo;
begin
// Fetch all users from the database as TUserInfo objects
UsersList := TQryRecInfo.FetchAll<TUserInfo>(DBConn, UserQuery);
try
for User in UsersList do
begin
// Access properties like ID, Name, Age through the TUserInfo properties
if User.ID.HasValue then
Writeln('User ID: ', User.ID.Value);
if User.Name.HasValue then
Writeln('Name: ', User.Name.Value);
if User.Age.HasValue then
Writeln('Age: ', User.Age.Value);
Writeln('---');
end;
finally
UsersList.Free;
end;
end;
This example demonstrates how to use generics to dynamically instantiate and populate objects of any descendant of TQryRecInfo while still benefiting from the flexible handling of nullable types provided by the base class methods.
class function TQryRecInfo.FetchAll<T: TQryRecInfo, constructor>(DBConn: TUniConnection; const QryTxt: string): TObjectList<T>;
var
qr: TUniQuery;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
NullableFieldName: string;
RecInfo: T;
begin
Result := TObjectList<T>.Create(True); // Owns objects
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(T);
qr.First;
while not qr.Eof do
begin
RecInfo := T.Create;
try
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
NullableFieldName := '_' + Prop.Name;
if ObjType.GetField(NullableFieldName) = nil then
Continue;
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
if Field.IsNull then
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Variant>>(NullValue));
end
else
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Variant>>(Field.Value));
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:
Prop.SetValue(RecInfo, Field.AsString);
tkInteger:
Prop.SetValue(RecInfo, Field.AsInteger);
tkInt64:
Prop.SetValue(RecInfo, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
Prop.SetValue(RecInfo, Field.AsCurrency)
else
Prop.SetValue(RecInfo, Field.AsFloat);
tkVariant:
Prop.SetValue(RecInfo, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
Prop.SetValue(RecInfo, 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;
Result.Add(RecInfo);
except
RecInfo.Free;
raise;
end;
qr.Next;
end;
finally
// No need to free TRttiContext as it's a record
end;
end;
finally
qr.Free;
end;
end;
Explanation
Generic Constraint: The constraint T: TQryRecInfo, constructor indicates that T must be derived from TQryRecInfo and must have a parameterless constructor.
Usage in a Method: When calling this generic method, you will specify the class type for T, such as TUserInfo, allowing for dynamic instance creation using T.Create.
With this setup, you can use the FetchAll function with any class deriving from TQryRecInfo. This flexibility allows you to create type-safe lists containing different types of records without sacrificing the ability to instantiate the objects dynamically.
class function TQryRecInfo.FetchAll<T: TQryRecInfo>(DBConn: TUniConnection; const QryTxt: string): TObjectList<T>;
var
qr: TUniQuery;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
NullableFieldName: string;
RecInfo: T;
begin
// Ensure the class has a parameterless constructor
Result := TObjectList<T>.Create(True);
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(T);
qr.First;
while not qr.Eof do
begin
RecInfo := T.Create; // Create instance of the generic type
try
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
NullableFieldName := '_' + Prop.Name;
if ObjType.GetField(NullableFieldName) = nil then
Continue;
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
if Field.IsNull then
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Variant>>(NullValue));
end
else
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Variant>>(Field.Value));
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:
Prop.SetValue(RecInfo, Field.AsString);
tkInteger:
Prop.SetValue(RecInfo, Field.AsInteger);
tkInt64:
Prop.SetValue(RecInfo, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
Prop.SetValue(RecInfo, Field.AsCurrency)
else
Prop.SetValue(RecInfo, Field.AsFloat);
tkVariant:
Prop.SetValue(RecInfo, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
Prop.SetValue(RecInfo, 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;
Result.Add(RecInfo);
except
RecInfo.Free;
raise;
end;
qr.Next;
end;
finally
// No need to free TRttiContext as it's a record
end;
end;
finally
qr.Free;
end;
end;
Key Points:
Generic Constraints: Make sure the constraint for generics is properly specified. Here, we only specify T: TQryRecInfo as the constraint. The constructor constraint is implied by our use of T.Create for instantiation.
Instantiation: Using T.Create assumes T has a default constructor, which your derived classes must ensure.
Type Handling: This implementation loop through properties of T to correctly set values from the query result.
Usage Example
When calling this method, specify your class type as you did before:
pascal
procedure RetrieveUsers(DBConn: TUniConnection);
const
UserQuery = 'SELECT ID, Name, Age FROM Users';
var
UsersList: TObjectList<TUserInfo>;
User: TUserInfo;
begin
// Use FetchAll with the descendant type
UsersList := TQryRecInfo.FetchAll<TUserInfo>(DBConn, UserQuery);
try
for User in UsersList do
begin
// Check if the values are set and then use them
if User.ID.HasValue then
Writeln('User ID: ', User.ID.Value);
if User.Name.HasValue then
Writeln('Name: ', User.Name.Value);
if User.Age.HasValue then
Writeln('Age: ', User.Age.Value);
Writeln('---');
end;
finally
UsersList.Free;
end;
end;
With these changes, this should allow the generic FetchAll function to handle any descendant of TQryRecInfo as long as they comply with the constraints implied by the constructor usage (i.e., have a parameterless constructor). Make sure all necessary fields and properties are correctly defined in your derived classes.
class function TQryRecInfo.FetchAll<T: TQryRecInfo, constructor>(DBConn: TUniConnection; const QryTxt: string): TObjectList<T>;
var
qr: TUniQuery;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
NullableFieldName: string;
RecInfo: T;
begin
Result := TObjectList<T>.Create(True); // Owns objects
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(T);
qr.First;
while not qr.Eof do
begin
RecInfo := T.Create; // Create instance of the generic type
try
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
NullableFieldName := '_' + Prop.Name;
if ObjType.GetField(NullableFieldName) = nil then
Continue;
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
if Field.IsNull then
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(NullValue))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Variant>>(NullValue));
end
else
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Variant>>(Field.Value));
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:
Prop.SetValue(RecInfo, Field.AsString);
tkInteger:
Prop.SetValue(RecInfo, Field.AsInteger);
tkInt64:
Prop.SetValue(RecInfo, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
Prop.SetValue(RecInfo, Field.AsCurrency)
else
Prop.SetValue(RecInfo, Field.AsFloat);
tkVariant:
Prop.SetValue(RecInfo, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
Prop.SetValue(RecInfo, 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;
Result.Add(RecInfo);
except
RecInfo.Free;
raise;
end;
qr.Next;
end;
finally
// No need to free TRttiContext as it's a record
end;
end;
finally
qr.Free;
end;
end;
Key Changes:
Generic Constraints: Using <T: TQryRecInfo, constructor> places a single constraint block, ensuring T is a descendant of TQryRecInfo and has a default constructor.
Instantiation: Using T.Create to ensure instances are created correctly requires the constructor constraint.
With these changes, your code should compile correctly, allowing you to generically fetch records into objects of any class deriving from TQryRecInfo.