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;
Assistant
User
I have found an error on an example I tested:
[dcc32 Error] ORM_Test.pas(253): E2010 Incompatible types: 'TObjectList' and 'System.Generics.Collections.TObjectList<orm_utils.TQryRecInfo>'
procedure ORM_Test8;
procedure RetrieveUsers(DBConn: TUniConnection);
const
UserQuery = 'SELECT employeename,employeeid,departmentid,projectid,projectname,projectbudget,projectdate,projectstartmoment,projectbudget * 2 as budgetlimit FROM orm_employee';
var
UsersList: TObjectList;
User: TEmployeeProject;
begin
// Fetch all users from the database
UsersList := TEmployeeProject.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;
begin
RetrieveUsers(DM.LocalServer);
end;
Assistant
User
create a complete unit with the usage example
Assistant
User
It it not working use generics to handle the descendants of TQryRecInfo
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// 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
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;
class function TQryRecInfo.FetchAll(DBConn: TUniConnection; const QryTxt: string): TObjectList;
var
qr: TUniQuery;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
NullableFieldName: string;
RecInfo: TQryRecInfo;
begin
Result := TObjectList.Create(True); // Owns objects
if not Assigned(DBConn) or Trim(QryTxt).IsEmpty then
Exit;
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;
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]);
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.
Review and fix the Fetall function
The FetchAll function implemented in the unit seems mostly correct, but it could benefit from a few improvements and clarifications to ensure robustness, readability, and better handling of exceptions. Here is the revised version with comments explaining changes:
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);
// Loop through each record
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
// Check for nulls and set TNullable accordingly
if Field.IsNull then
begin
// Set nullable to NullValue
if Prop.PropertyType.Handle = TypeInfo(TNullable<string>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(NullValue))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Integer>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(NullValue))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Int64>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(NullValue))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Extended>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(NullValue))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Currency>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(NullValue))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<TDateTime>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(NullValue))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Boolean>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(NullValue))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Variant>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Variant>>(NullValue));
end
else
begin
// Set nullable with actual field value
if Prop.PropertyType.Handle = TypeInfo(TNullable<string>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Integer>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Int64>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Extended>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Currency>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<TDateTime>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Boolean>) then
ObjType.GetField(NullableFieldName).SetValue(RecInfo, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<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 property 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 handling for additional types as needed
end;
end;
end;
Result.Add(RecInfo);
except
on E: Exception do
begin
RecInfo.Free;
raise EORMUtilsException.CreateFmt('Error processing record: %s', [E.Message]);
end;
end;
qr.Next;
end;
finally
// No need to explicitly free TRttiContext as it is a record
end;
end;
finally
qr.Free;
end;
end;
Key Changes and Improvements
Error Handling: Surround RecInfo processing in a try...except to ensure exceptions do not leave objects partially constructed.
Nullable Field Handling: Updated checks for TNullable<T> types to verify that NullableFieldName exists before setting values.
Type Checks: Used Prop.PropertyType.Handle instead of Prop.PropertyType.Name to compare types in a more Delphi-idiomatic way.
Robustness: Added checks to ensure fields are assignable and to exclude unsupported record types properly.
By implementing these enhancements, the function becomes more robust, readable, and aligns better with the standard Pascal error handling practices.
The error message indicates a type mismatch between TObjectList<TEmployeeProject> and TObjectList<orm_utils.TQryRecInfo>. This suggests that TEmployeeProject is likely intended to inherit from or be compatible with TQryRecInfo, but they are currently separate types.
To resolve this issue, you need to ensure that TEmployeeProject either directly inherits from TQryRecInfo or provides a way to convert or adapt the results from FetchAll.
Here's a general approach to fix this:
Inheritance: If TEmployeeProject should logically inherit from TQryRecInfo, make it a descendant class. This way, TEmployeeProject will directly inherit the methods and properties of TQryRecInfo, allowing the type compatibility needed for the object list.
Type Conversion: Alternatively, if TEmployeeProject shouldn't inherit from TQryRecInfo, you can implement a conversion or creation method that transforms instances of TQryRecInfo to TEmployeeProject.
Here's a hypothetical example with inheritance:
Inheritance Approach
type
TEmployeeProject = class(TQryRecInfo)
public
// Define additional properties or methods if needed
function GetEmployeeName: string; inline;
function GetEmployeeID: Integer; inline;
// Other methods specific to TEmployeeProject
end;
// Implement any additional methods needed by TEmployeeProject
function TEmployeeProject.GetEmployeeName: string;
begin
Result := GetFormattedText('EmployeeName');
end;
function TEmployeeProject.GetEmployeeID: Integer;
begin
Result := GetFormattedText('EmployeeID').ToInteger;
end;
// Usage
procedure RetrieveUsers(DBConn: TUniConnection);
const
UserQuery = 'SELECT employeename,employeeid,departmentid,projectid,projectname,projectbudget,projectdate,projectstartmoment,projectbudget * 2 as budgetlimit FROM orm_employee';
var
UsersList: TObjectList<TEmployeeProject>;
User: TEmployeeProject;
begin
// Cast the results to TEmployeeProject if FetchAll returns TQryRecInfo objects
UsersList := TObjectList<TEmployeeProject>(TEmployeeProject.FetchAll(DBConn, UserQuery));
try
for User in UsersList do
begin
Writeln('User ID: ', User.GetEmployeeID);
Writeln('Name: ', User.GetEmployeeName);
// Add more formatted outputs
Writeln('---');
end;
finally
UsersList.Free;
end;
end;
Adapter/Conversion Approach
If you don't want TEmployeeProject to directly inherit from TQryRecInfo, you'll need to implement an adapter or mapper function to convert TQryRecInfo instances into TEmployeeProject instances.
function ConvertToEmployeeProject(RecInfo: TQryRecInfo): TEmployeeProject;
begin
Result := TEmployeeProject.Create;
try
// Extract fields from RecInfo into Result
// Use appropriate getters to transform data
Result.EmployeeName := RecInfo.GetFormattedText('EmployeeName');
Result.EmployeeID := RecInfo.GetFormattedText('EmployeeID').ToInteger;
// Similarly, load other necessary fields
except
Result.Free;
raise;
end;
end;
// Usage
procedure RetrieveUsers(DBConn: TUniConnection);
const
UserQuery = 'SELECT employeename,employeeid... FROM orm_employee';
var
RecList: TObjectList<TQryRecInfo>;
UsersList: TObjectList<TEmployeeProject>;
Rec: TQryRecInfo;
begin
RecList := TQryRecInfo.FetchAll(DBConn, UserQuery);
UsersList := TObjectList<TEmployeeProject>.Create;
try
for Rec in RecList do
begin
UsersList.Add(ConvertToEmployeeProject(Rec));
end;
for User in UsersList do
begin
Writeln('User ID: ', User.GetEmployeeID);
Writeln('Name: ', User.GetEmployeeName);
// Add more formatted outputs
Writeln('---');
end;
finally
RecList.Free;
UsersList.Free;
end;
end;
Choose the strategy that best fits your application architecture. The inheritance method is cleaner if TEmployeeProject is a specialized version of TQryRecInfo, while the adapter method is helpful if you need more flexibility or encapsulation.
Certainly! Below is a complete Delphi unit that demonstrates how to define TEmployeeProject as a descendant of TQryRecInfo, along with an example usage that retrieves and prints employee information.
This example assumes you have a proper setup with ORM utilities and the database connection components you mentioned.
unit ORM_Example;
interface
uses
System.Classes,
System.Generics.Collections,
System.SysUtils,
Uni, // Assuming TUniConnection and TUniQuery are available
orm_utils; // Assuming this unit contains TQryRecInfo and other necessary utilities
type
// Define TEmployeeProject inheriting from TQryRecInfo
TEmployeeProject = class(TQryRecInfo)
public
function GetEmployeeName: string; inline;
function GetEmployeeID: Integer; inline;
function GetDepartmentID: Integer; inline;
function GetProjectName: string; inline;
end;
procedure RetrieveUsers(DBConn: TUniConnection);
implementation
{ TEmployeeProject }
function TEmployeeProject.GetEmployeeName: string;
begin
Result := GetFormattedText('EmployeeName');
end;
function TEmployeeProject.GetEmployeeID: Integer;
begin
Result := GetFormattedText('EmployeeID').ToInteger;
end;
function TEmployeeProject.GetDepartmentID: Integer;
begin
Result := GetFormattedText('DepartmentID').ToInteger;
end;
function TEmployeeProject.GetProjectName: string;
begin
Result := GetFormattedText('ProjectName');
end;
procedure RetrieveUsers(DBConn: TUniConnection);
const
UserQuery = 'SELECT EmployeeName, EmployeeID, DepartmentID, ProjectName, ' +
'ProjectBudget, ProjectDate, ProjectStartMoment ' +
'FROM orm_employee';
var
UsersList: TObjectList<TEmployeeProject>;
User: TEmployeeProject;
begin
// Fetch all users from the database
UsersList := TObjectList<TEmployeeProject>(TEmployeeProject.FetchAll(DBConn, UserQuery));
try
for User in UsersList do
begin
Writeln('User ID: ', User.GetEmployeeID);
Writeln('Name: ', User.GetEmployeeName);
Writeln('Department ID: ', User.GetDepartmentID);
Writeln('Project Name: ', User.GetProjectName);
Writeln('---');
end;
finally
UsersList.Free;
end;
end;
end.
Explanation
Inheritance: The TEmployeeProject class is inherited from TQryRecInfo. It adds methods to retrieve formatted text for specific properties like EmployeeName, EmployeeID, etc.
FetchAll: The FetchAll method is used to fetch records from the database and directly cast the returned list to TObjectList<TEmployeeProject>. This assumes that FetchAll in TEmployeeProject is working correctly via inheritance and properly handles initialization.
Use of System Utilities: Make sure the necessary Delphi units like SysUtils, Classes, Generics.Collections, and Uni components are available for use.
Database Connection: The RetrieveUsers procedure takes a TUniConnection as a parameter, ensuring it is connected to the appropriate database before executing the query.
Note
Ensure that your Delphi environment is properly set up to use the components mentioned, such as TUniConnection and TUniQuery, typically part of a database connectivity library. Adjust SQL queries and field names to fit your database schema.
To handle different descendants of TQryRecInfo using generics, you can define a generic FetchAll method in a way that it can return lists of any class that descends from TQryRecInfo. This approach leverages generics in Delphi to create a more flexible and reusable utility. Here is how you might set that up:
Updated Delphi Unit with Generics
unit ORM_Example_Generic;
interface
uses
System.Classes,
System.Generics.Collections,
System.SysUtils,
System.Rtti,
Uni, // Assuming TUniConnection and TUniQuery are available
orm_utils; // Assuming this unit contains TQryRecInfo and other necessary utilities
type
// Define TEmployeeProject inheriting from TQryRecInfo
TEmployeeProject = class(TQryRecInfo)
public
function GetEmployeeName: string; inline;
function GetEmployeeID: Integer; inline;
function GetDepartmentID: Integer; inline;
function GetProjectName: string; inline;
end;
// Helper function to fetch records as objects of type T
generic function FetchEntities<T: TQryRecInfo, constructor>(DBConn: TUniConnection; const QryTxt: string): TObjectList<T>;
procedure RetrieveUsers(DBConn: TUniConnection);
implementation
{ TEmployeeProject }
function TEmployeeProject.GetEmployeeName: string;
begin
Result := GetFormattedText('EmployeeName');
end;
function TEmployeeProject.GetEmployeeID: Integer;
begin
Result := GetFormattedText('EmployeeID').ToInteger;
end;
function TEmployeeProject.GetDepartmentID: Integer;
begin
Result := GetFormattedText('DepartmentID').ToInteger;
end;
function TEmployeeProject.GetProjectName: string;
begin
Result := GetFormattedText('ProjectName');
end;
// Generic function to fetch entities
generic function FetchEntities<T>(DBConn: TUniConnection; const QryTxt: string): TObjectList<T>;
var
qr: TUniQuery;
Rec: T;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
begin
Result := TObjectList<T>.Create; // Owns objects
if not Assigned(DBConn) or Trim(QryTxt).IsEmpty then
Exit;
qr := TUniQuery.Create(nil);
try
qr.Connection := DBConn;
qr.SQL.Text := QryTxt;
qr.Open;
Ctx := TRttiContext.Create;
try
ObjType := Ctx.GetType(TClass(T));
while not qr.Eof do
begin
Rec := 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 basic types; modify as per real implementation
case Prop.PropertyType.TypeKind of
tkString, tkLString, tkWString, tkUString:
Prop.SetValue(Rec, Field.AsString);
tkInteger:
Prop.SetValue(Rec, Field.AsInteger);
tkInt64:
Prop.SetValue(Rec, Field.AsLargeInt);
tkFloat:
Prop.SetValue(Rec, Field.AsFloat);
tkVariant:
Prop.SetValue(Rec, TValue.FromVariant(Field.Value));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
Prop.SetValue(Rec, Field.AsBoolean);
else
// Expand as needed for additional types
end;
end;
Result.Add(Rec);
except
Rec.Free;
raise;
end;
qr.Next;
end;
finally
// No need to explicitly free TRttiContext as it is automatically managed
end;
finally
qr.Free;
end;
end;
// Usage example
procedure RetrieveUsers(DBConn: TUniConnection);
const
UserQuery = 'SELECT EmployeeName, EmployeeID, DepartmentID, ProjectName FROM orm_employee';
var
UsersList: TObjectList<TEmployeeProject>;
User: TEmployeeProject;
begin
// Use the generic function to fetch TEmployeeProject entities
UsersList := FetchEntities<TEmployeeProject>(DBConn, UserQuery);
try
for User in UsersList do
begin
Writeln('User ID: ', User.GetEmployeeID);
Writeln('Name: ', User.GetEmployeeName);
Writeln('Department ID: ', User.GetDepartmentID);
Writeln('Project Name: ', User.GetProjectName);
Writeln('---');
end;
finally
UsersList.Free;
end;
end;
end.
Key Points
Generic Function: FetchEntities<T> is defined to handle any class T that descends from TQryRecInfo. This function uses RTTI to read properties from the database result set into instances of T.
TObjectList: The FetchEntities<T> function returns a TObjectList<T>, allowing it to work with any specific type derived from TQryRecInfo.
Usage: The RetrieveUsers procedure shows how to fetch TEmployeeProject objects using the generic function. It demonstrates how entities can be instantiated and managed.
Ensure that your database and ORM setup are compatible with this approach, especially being able to map field names in your SQL queries to the properties in your Delphi classes correctly. This method provides a flexible and reusable way to handle various entity types without needing to duplicate fetch logic.