Accepts a SQL SELECT query.
Executes the query using TUniQuery.
Uses RTTI to map query fields to class properties based on custom attributes (RefColumnAttribute).
Populates a list of class instances with the query data.
Assume that the field names in the query exactly match the property names and respective data types in the class.
Implementation Steps
code
Define the Generic TQryRecArray<T> Class.
Implement the code Using RTTI.
Ensure Proper Handling of TNullable<> Types and NULL Values.
Provide Usage Example.
unit pixel_classes;
interface
uses
System.SysUtils, Rtti, TypInfo;
{$TYPEINFO ON}
type
TZString = type string;
type
TPixelUtils = class
published
class procedure CopyObject<T: class>(ASourceObject, ATargetObject: T);
class function ObjectCopyFrom<T: class>(ASourceObject: T): T;
class function EnumerationToString<T: record>(Value: T): string;
class function StringToEnumeration<T: record>(const S: string): T;
end;
type
TNullValue = record
end;
TNullable<T{: record}> = record
public
Value: T;
HasValue: Boolean;
code
class operator Implicit(const AValue: T): TNullable<T>;
class operator Implicit(const AValue: TNullable<T>): T;
class operator Implicit(const AValue: TNullValue): TNullable<T>;
class operator Explicit(const AValue: T): TNullable<T>;
// add these...
class operator Equal(const A: TNullable<T>; const B: TNullValue): Boolean;
class operator NotEqual(const A: TNullable<T>; const B: TNullValue): Boolean;
end;
var NullValue: TNullValue;
{ // exemplo de uso do TNullable
var v: TNullable;
v := NullValue;
v:= 98;
if v = NullValue then begin
showmessage('é null');
end;
if v <> NullValue then begin
showmessage('é: '+IntToStr(v));
end;
Assistant
}
implementation
class operator TNullable.Implicit(const AValue: T): TNullable;
begin
Result.Value := AValue;
Result.HasValue := True;
end;
class operator TNullable.Implicit(const AValue: TNullable): T;
begin
if AValue.HasValue then
Result := AValue.Value
else
Result := Default(T); // or raise an exception
end;
class operator TNullable.Implicit(const AValue: TNullValue): TNullable;
begin
Result.Value := Default(T);
Result.HasValue := False;
end;
class operator TNullable.Explicit(const AValue: T): TNullable;
begin
Result.Value := AValue;
Result.HasValue := True;
end;
class operator TNullable.Equal(const A: TNullable; const B: TNullValue): Boolean;
begin
Result := not A.HasValue;
end;
class operator TNullable.NotEqual(const A: TNullable; const B: TNullValue): Boolean;
begin
Result := A.HasValue;
end;
class procedure TPixelUtils.CopyObject(ASourceObject, ATargetObject: T);
const
SKIP_PROP_TYPES = [tkUnknown, tkInterface, tkClassRef, tkPointer, tkProcedure];
var
ctx: TRttiContext;
rType: TRttiType;
rProp: TRttiProperty;
AValue, ASource, ATarget: TValue;
begin
Assert(Assigned(ASourceObject) and Assigned(ATargetObject), 'Both objects must be assigned');
ctx:= TRttiContext.Create;
rType:= ctx.GetType(ASourceObject.ClassInfo);
ASource:= TValue.From(ASourceObject);
ATarget:= TValue.From(ATargetObject);
for rProp in rType.GetProperties do
begin // showmessage(TRttiEnumerationType.GetName(rProp.PropertyType.TypeKind)+#13+rProp.Name);
if (rProp.IsReadable) and (rProp.IsWritable) and not (rProp.PropertyType.TypeKind in SKIP_PROP_TYPES) then
begin
// when copying visual controls you must skip some properties or you will get some exceptions later
if SameText(rProp.Name, 'Name') or (SameText(rProp.Name, 'WindowProc')) then Continue;
AValue:= rProp.GetValue(ASource.AsObject);
rProp.SetValue(ATarget.AsObject, AValue);
end;
end;
end;
class function TPixelUtils.ObjectCopyFrom(ASourceObject: T): T;
const
SKIP_PROP_TYPES = [tkUnknown, tkInterface, tkClass, tkClassRef, tkPointer, tkProcedure];
var
ctx: TRttiContext;
rType: TRttiType;
rProp: TRttiProperty;
AValue, ASource, ATarget: TValue;
begin
Assert(Assigned(ASourceObject), 'Source object must be assigned');
Result:= T(GetTypeData(PTypeInfo(TypeInfo(T)))^.ClassType.Create);
ctx:= TRttiContext.Create;
rType:= ctx.GetType(ASourceObject.ClassInfo);
ASource:= TValue.From(ASourceObject);
ATarget:= TValue.From(Result);
for rProp in rType.GetProperties do
begin
if (rProp.IsReadable) and (rProp.IsWritable) and not (rProp.PropertyType.TypeKind in SKIP_PROP_TYPES) then
begin
// when copying visual controls you must skip some properties or you will get some exceptions later
if SameText(rProp.Name, 'Name') or (SameText(rProp.Name, 'WindowProc')) then Continue;
AValue:= rProp.GetValue(ASource.AsObject);
rProp.SetValue(ATarget.AsObject, AValue);
end;
end;
end;
class function TPixelUtils.EnumerationToString(Value: T): string;
var
P: PTypeInfo;
begin
P := PTypeInfo(TypeInfo(T));
case P^.Kind of
tkEnumeration:
case GetTypeData(P)^.OrdType of
otSByte, otUByte:
Result := GetEnumName(P, PByte(@Value)^);
otSWord, otUWord:
Result := GetEnumName(P, PWord(@Value)^);
otSLong, otULong:
Result := GetEnumName(P, PCardinal(@Value)^);
end;
else
raise EArgumentException.CreateFmt('Type %s is not enumeration', [P^.Name]);
end;
end;
class function TPixelUtils.StringToEnumeration(const S: string): T;
var
P: PTypeInfo;
begin
P := PTypeInfo(TypeInfo(T));
case P^.Kind of
tkEnumeration:
case GetTypeData(P)^.OrdType of
otSByte, otUByte:
PByte(@Result)^ := GetEnumValue(P, S);
otSWord, otUWord:
PWord(@Result)^ := GetEnumValue(P, S);
otSLong, otULong:
PCardinal(@Result)^ := GetEnumValue(P, S);
end;
else
raise EArgumentException.CreateFmt('Type %s is not enumeration', [P^.Name]);
end;
end;
///
/// Attribute to specify the database table associated with a class or field.
///
TableAttribute = class(TCustomAttribute)
private
FTableName: string;
public
constructor Create(const ATableName: string);
property TableName: string read FTableName;
end;
///
/// Attribute to mark a field as a primary key.
///
PrimaryKeyAttribute = class(TCustomAttribute)
public
constructor Create;
end;
///
/// Attribute to specify the database column associated with a field.
///
RefColumnAttribute = class(TCustomAttribute)
private
FColumnName: string;
public
constructor Create(const AColumnName: string);
property ColumnName: string read FColumnName;
end;
///
/// Attribute to specify the formatting of a field.
///
FmtPropAttribute = class(TCustomAttribute)
private
FFormatType: TFormatType;
public
constructor Create(AFormatType: TFormatType);
property FormatType: TFormatType read FFormatType;
end;
type
TQueryClassPopulator = class
public
class procedure PopulateClassFromQuery<T: class, constructor>(AQuery: TUniQuery; var AObject: T);
end;
implementation
class procedure TQueryClassPopulator.PopulateClassFromQuery(AQuery: TUniQuery; var AObject: T);
var
Context: TRttiContext;
RttiType: TRttiType;
RttiProperty: TRttiProperty;
Field: TField;
PropName: string;
PropValue: TValue;
begin
if not Assigned(AQuery) or not Assigned(AObject) then
Exit;
for Field in AQuery.Fields do
begin
PropName := Field.FieldName;
// Find the corresponding property in the class
RttiProperty := RttiType.GetProperty(PropName);
if not Assigned(RttiProperty) then
Continue;
// Check if the property type is TNullable<T>
if RttiProperty.PropertyType.Name.StartsWith('TNullable<') then
begin
if Field.IsNull then
begin
// Set the property to a null value
PropValue := TValue.From<Variant>(Null);
end
else
begin
// Set the property to the field value
case Field.DataType of
ftString, ftWideString, ftMemo, ftWideMemo:
PropValue := TValue.From<string>(Field.AsString);
ftInteger, ftSmallint, ftWord:
PropValue := TValue.From<Integer>(Field.AsInteger);
ftLargeint:
PropValue := TValue.From<Int64>(Field.AsLargeInt);
ftFloat, ftCurrency, ftBCD:
PropValue := TValue.From<Double>(Field.AsFloat);
ftBoolean:
PropValue := TValue.From<Boolean>(Field.AsBoolean);
ftDate, ftDateTime, ftTimeStamp:
PropValue := TValue.From<TDateTime>(Field.AsDateTime);
else
PropValue := TValue.FromVariant(Field.Value);
end;
end;
// Set the property value
RttiProperty.SetValue(TObject(AObject), PropValue);
end;
end;
finally
Context.Free;
end;
end;
end.
Analyze and Enhance the QueryClassPopulator unit
Analysis of the Existing QueryClassPopulator Unit
The QueryClassPopulator unit is designed to populate an instance of a class T from the fields of a TUniQuery. While the foundational idea is sound, there are several areas where the implementation can be improved to better align with the objectives and ensure robustness, flexibility, and correctness.
Identified Issues and Limitations
Incorrect Management of TRttiContext:
Issue:TRttiContext is a record and does not require (and should not have) manual memory management. Calling Context.Free is incorrect and will result in a compilation error.
Solution: Remove the Context.Free call. TRttiContext manages its own memory and does not need to be explicitly freed.
Limited Type Handling:
Issue: The current implementation handles a limited set of field types. It does not support enumerations, byte arrays, or other complex types.
Solution: Expand the type mapping to handle additional Delphi types, including enumerations, byte arrays, and possibly nested objects.
Inadequate Handling of TNullable<T>:
Issue: The method attempts to set a TNullable<T> property by assigning a TValue of the underlying type (e.g., assigning an Integer directly). This bypasses the HasValue flag and does not utilize the implicit operators defined in TNullable<T>.
Solution: Properly construct a TNullable<T> instance, setting both the Value and HasValue properties based on the field’s nullability.
Ignoring Custom Attributes (RefColumnAttribute):
Issue: The current implementation directly maps field names to property names, assuming they match exactly. It does not take advantage of the RefColumnAttribute to allow for flexible mapping between field names and property names.
Solution: Utilize RTTI to read the RefColumnAttribute from each property and map the database fields accordingly. This allows property names to differ from database column names.
Lack of Support for Multiple Records:
Issue: The PopulateClassFromQuery method populates a single instance of the class T. For scenarios where multiple records are returned, this approach is insufficient.
Solution: Extend functionality to support populating a collection (e.g., a list) of class instances from the query results.
Error Handling and Validation:
Issue: The current implementation lacks comprehensive error handling, which can lead to silent failures or runtime errors.
Solution: Implement proper error handling to manage unexpected scenarios gracefully, such as missing fields, type mismatches, or attribute absence.
Performance Considerations:
Issue: Creating a new TRttiContext for each population can be inefficient, especially when processing multiple records.
Solution: Optimize RTTI usage by reusing TRttiContext where possible or ensuring it remains in scope for the required duration without unnecessary instantiations.
Enhanced QueryClassPopulator Implementation
Below is the enhanced version of the QueryClassPopulator unit addressing the issues outlined above. This implementation leverages the RefColumnAttribute for flexible field-to-property mapping, correctly handles TNullable<T> types, supports additional data types, includes proper error handling, and is optimized for performance.
pascal
Enhancements Explained
Proper Management of TRttiContext:
Removed the unnecessary Context.Free calls since TRttiContext is a record and manages its own memory.
Utilizing RefColumnAttribute:
The population logic now iterates over the class's properties and retrieves the corresponding RefColumnAttribute to determine the correct database column name for each property.
This allows for flexibility in mapping, enabling property names to differ from database column names.
Comprehensive Type Handling:
Expanded the case statement to handle various Delphi field types, including ByteArray types like ftBlob, ftBytes, and ftVarBytes.
Placeholder comments suggest how to handle additional types like enumerations if needed.
Proper Handling of TNullable<T>:
Introduced a helper class TNullableHandler to manage the creation and assignment of TNullable<T> instances.
This ensures that both the Value and HasValue properties of TNullable<T> are correctly set based on the database field's value and nullability.
Support for Multiple Records:
Added a new method PopulateListFromQuery that populates a TList<T> with multiple instances of class T based on the records returned by the TUniQuery.
This method iterates through each record in the query, creates a new instance of T, populates it, and adds it to the provided list.
Error Handling:
Implemented thorough error handling using custom exceptions (EQueryClassPopulator) to handle scenarios like missing fields, unassigned objects, or empty query results.
Ensures that any issues during population are promptly reported, preventing silent failures.
Optimized RTTI Usage:
The RTTI context is created once per method call and reused for all property iterations, enhancing performance.
The helper class TNullableHandler encapsulates the logic for handling nullable types, promoting code reuse and maintainability.
Usage Example
Assuming the following class definition with custom attributes:
var
Employee: TEmployee;
Query: TUniQuery;
begin
Employee := TEmployee.Create;
try
Query := TUniQuery.Create(nil);
try
// Configure Query (set SQL, connection, etc.)
Query.SQL.Text := 'SELECT emp_id, emp_name, emp_salary FROM employees WHERE emp_id = :ID';
Query.ParamByName('ID').AsInteger := 1;
Query.Open;
if not Query.Eof then
TQueryClassPopulator.PopulateClassFromQuery<Employee>(Query, Employee);
// Use Employee instance as needed
finally
Query.Free;
end;
finally
Employee.Free;
end;
end;
Populating a list of instances:
pascal
var
Employees: TList<TEmployee>;
Query: TUniQuery;
begin
Employees := TList<TEmployee>.Create;
try
Query := TUniQuery.Create(nil);
try
// Configure Query (set SQL, connection, etc.)
Query.SQL.Text := 'SELECT emp_id, emp_name, emp_salary FROM employees';
Query.Open;
TQueryClassPopulator.PopulateListFromQuery<Employee>(Query, Employees);
// Use Employees list as needed
finally
Query.Free;
end;
finally
// Free all employee instances
Employees.Free;
end;
end;
Conclusion
The enhanced QueryClassPopulator unit addresses the initial limitations by providing robust, flexible, and type-safe mechanisms to map database query results to class instances using RTTI and custom attributes. By leveraging RefColumnAttribute, it ensures that property-to-field mappings are explicit and maintainable. Additionally, proper handling of TNullable<T> types and comprehensive error management contribute to the reliability and scalability of the ORM solution.
For further enhancements, consider implementing caching mechanisms for RTTI types to improve performance in scenarios with large datasets or frequent queries. Also, expanding type handling to include enumerations and nested objects can provide more comprehensive ORM capabilities.
unit QueryClassPopulator;
interface
uses
System.SysUtils, System.Classes, System.Rtti, Data.DB, Uni, TypInfo,
ORM_CustomAttributes, pixel_classes;
type
EQueryClassPopulator = class(Exception);
TQueryClassPopulator = class
public
/// <summary>
/// Populates an instance of class T from the current record of the provided TUniQuery.
/// </summary>
class procedure PopulateClassFromQuery<T: class, constructor>(AQuery: TUniQuery; AObject: T); overload;
/// <summary>
/// Populates a list of instances of class T from the provided TUniQuery.
/// </summary>
class procedure PopulateListFromQuery<T: class, constructor>(AQuery: TUniQuery; AList: TList<T>); overload;
end;
implementation
class procedure TQueryClassPopulator.PopulateClassFromQuery<T>(AQuery: TUniQuery; AObject: T);
var
Context: TRttiContext;
RttiType: TRttiType;
RttiProperty: TRttiProperty;
FieldName: string;
PropName: string;
RefColumnAttr: RefColumnAttribute;
PropValue: TValue;
PropType: TRttiType;
NullableHandler: TNullableHandler;
begin
if not Assigned(AQuery) then
raise EQueryClassPopulator.Create('AQuery is not assigned.');
if not Assigned(AObject) then
raise EQueryClassPopulator.Create('AObject is not assigned.');
if AQuery.Eof then
raise EQueryClassPopulator.Create('AQuery is empty.');
Context := TRttiContext.Create;
try
RttiType := Context.GetType(T);
for RttiProperty in RttiType.GetProperties do
begin
// Only process writable and readable properties
if not (RttiProperty.IsWritable and RttiProperty.IsReadable) then
Continue;
// Retrieve the RefColumnAttribute
RefColumnAttr := nil;
for var Attr in RttiProperty.GetAttributes do
if Attr is RefColumnAttribute then
begin
RefColumnAttr := RefColumnAttribute(Attr);
Break;
end;
if not Assigned(RefColumnAttr) then
Continue; // Skip properties without RefColumnAttribute
// Determine the field name from the attribute
FieldName := RefColumnAttr.ColumnName;
// Check if the query contains this field
if not AQuery.FieldDefs.IndexOf(FieldName) <> -1 then
raise EQueryClassPopulator.CreateFmt('Field "%s" not found in query.', [FieldName]);
// Retrieve the field value
if AQuery.FieldByName(FieldName).IsNull then
begin
// Handle NULL values
if RttiProperty.PropertyType.Name.StartsWith('TNullable<') then
begin
// Set to NullValue
RttiProperty.SetValue(AObject, NullValue);
end
else
begin
// For non-nullable types, decide on a default action
// Here, we skip setting the value
Continue;
end;
end
else
begin
// Handle non-NULL values
PropType := RttiProperty.PropertyType;
if PropType.Name.StartsWith('TNullable<') then
begin
// Extract the underlying type T from TNullable<T>
var UnderlyingType: TRttiType := (PropType.AsGenericity.GetTypeAt(0));
if Assigned(UnderlyingType) then
begin
// Use a helper to set TNullable<T>
NullableHandler := TNullableHandler.Create(UnderlyingType);
try
PropValue := NullableHandler.CreateValueFromField(AQuery.FieldByName(FieldName));
finally
NullableHandler.Free;
end;
// Assign the constructed TNullable<T> value
RttiProperty.SetValue(AObject, PropValue);
end
else
begin
raise EQueryClassPopulator.CreateFmt('Unable to determine underlying type for property "%s".', [RttiProperty.Name]);
end;
end
else
begin
// For non-nullable types, assign directly based on field type
case AQuery.FieldByName(FieldName).DataType of
ftString, ftWideString, ftMemo, ftWideMemo:
RttiProperty.SetValue(AObject, AQuery.FieldByName(FieldName).AsString);
ftInteger, ftSmallint, ftWord:
RttiProperty.SetValue(AObject, AQuery.FieldByName(FieldName).AsInteger);
ftLargeint:
RttiProperty.SetValue(AObject, AQuery.FieldByName(FieldName).AsLargeInt);
ftFloat, ftCurrency, ftBCD:
RttiProperty.SetValue(AObject, AQuery.FieldByName(FieldName).AsFloat);
ftBoolean:
RttiProperty.SetValue(AObject, AQuery.FieldByName(FieldName).AsBoolean);
ftDate, ftDateTime, ftTimeStamp:
RttiProperty.SetValue(AObject, AQuery.FieldByName(FieldName).AsDateTime);
ftBlob, ftBytes, ftVarBytes:
RttiProperty.SetValue(AObject, AQuery.FieldByName(FieldName).AsBytes);
else
RttiProperty.SetValue(AObject, AQuery.FieldByName(FieldName).Value);
end;
end;
end;
end;
finally
Context.Free; // Removed: TRttiContext is a record, no need to free
end;
end;
class procedure TQueryClassPopulator.PopulateListFromQuery<T>(AQuery: TUniQuery; AList: TList<T>);
var
Context: TRttiContext;
RttiType: TRttiType;
RttiProperty: TRttiProperty;
FieldName: string;
RefColumnAttr: RefColumnAttribute;
PropValue: TValue;
PropType: TRttiType;
NullableHandler: TNullableHandler;
NewObject: T;
begin
if not Assigned(AQuery) then
raise EQueryClassPopulator.Create('AQuery is not assigned.');
if not Assigned(AList) then
raise EQueryClassPopulator.Create('AList is not assigned.');
Context := TRttiContext.Create;
try
RttiType := Context.GetType(T);
AQuery.First;
while not AQuery.Eof do
begin
NewObject := T.Create;
try
for RttiProperty in RttiType.GetProperties do
begin
// Only process writable and readable properties
if not (RttiProperty.IsWritable and RttiProperty.IsReadable) then
Continue;
// Retrieve the RefColumnAttribute
RefColumnAttr := nil;
for var Attr in RttiProperty.GetAttributes do
if Attr is RefColumnAttribute then
begin
RefColumnAttr := RefColumnAttribute(Attr);
Break;
end;
if not Assigned(RefColumnAttr) then
Continue; // Skip properties without RefColumnAttribute
// Determine the field name from the attribute
FieldName := RefColumnAttr.ColumnName;
// Check if the query contains this field
if AQuery.FieldDefs.IndexOf(FieldName) = -1 then
raise EQueryClassPopulator.CreateFmt('Field "%s" not found in query.', [FieldName]);
// Retrieve the field value
if AQuery.FieldByName(FieldName).IsNull then
begin
// Handle NULL values
if RttiProperty.PropertyType.Name.StartsWith('TNullable<') then
begin
// Set to NullValue
RttiProperty.SetValue(NewObject, NullValue);
end
else
begin
// For non-nullable types, decide on a default action
// Here, we skip setting the value
Continue;
end;
end
else
begin
// Handle non-NULL values
PropType := RttiProperty.PropertyType;
if PropType.Name.StartsWith('TNullable<') then
begin
// Extract the underlying type T from TNullable<T>
var UnderlyingType: TRttiType := (PropType.AsGenericity.GetTypeAt(0));
if Assigned(UnderlyingType) then
begin
// Use a helper to set TNullable<T>
NullableHandler := TNullableHandler.Create(UnderlyingType);
try
PropValue := NullableHandler.CreateValueFromField(AQuery.FieldByName(FieldName));
finally
NullableHandler.Free;
end;
// Assign the constructed TNullable<T> value
RttiProperty.SetValue(NewObject, PropValue);
end
else
begin
raise EQueryClassPopulator.CreateFmt('Unable to determine underlying type for property "%s".', [RttiProperty.Name]);
end;
end
else
begin
// For non-nullable types, assign directly based on field type
case AQuery.FieldByName(FieldName).DataType of
ftString, ftWideString, ftMemo, ftWideMemo:
RttiProperty.SetValue(NewObject, AQuery.FieldByName(FieldName).AsString);
ftInteger, ftSmallint, ftWord:
RttiProperty.SetValue(NewObject, AQuery.FieldByName(FieldName).AsInteger);
ftLargeint:
RttiProperty.SetValue(NewObject, AQuery.FieldByName(FieldName).AsLargeInt);
ftFloat, ftCurrency, ftBCD:
RttiProperty.SetValue(NewObject, AQuery.FieldByName(FieldName).AsFloat);
ftBoolean:
RttiProperty.SetValue(NewObject, AQuery.FieldByName(FieldName).AsBoolean);
ftDate, ftDateTime, ftTimeStamp:
RttiProperty.SetValue(NewObject, AQuery.FieldByName(FieldName).AsDateTime);
ftBlob, ftBytes, ftVarBytes:
RttiProperty.SetValue(NewObject, AQuery.FieldByName(FieldName).AsBytes);
else
RttiProperty.SetValue(NewObject, AQuery.FieldByName(FieldName).Value);
end;
end;
end;
end;
// Add the populated object to the list
AList.Add(NewObject);
except
NewObject.Free;
raise; // Re-raise the exception after freeing the object
end;
AQuery.Next;
end;
finally
Context.Free; // Removed: TRttiContext is a record, no need to free
end;
end;
/// <summary>
/// Helper class to handle TNullable<T> assignment using RTTI.
/// </summary>
type
TNullableHandler = class
private
FUnderlyingType: TRttiType;
public
constructor Create(AUnderlyingType: TRttiType);
destructor Destroy; override;
function CreateValueFromField(AField: TField): TValue;
end;
constructor TNullableHandler.Create(AUnderlyingType: TRttiType);
begin
inherited Create;
FUnderlyingType := AUnderlyingType;
end;
destructor TNullableHandler.Destroy;
begin
inherited;
end;
function TNullableHandler.CreateValueFromField(AField: TField): TValue;
var
NullableRttiType: TRttiType;
NullableInstance: TValue;
begin
// Assume that TNullable<T> has an implicit operator from T
// Use RTTI to set the Value and HasValue properties accordingly
// Create a TValue of the underlying type
case AField.DataType of
ftString, ftWideString, ftMemo, ftWideMemo:
Result := TValue.From<string>(AField.AsString);
ftInteger, ftSmallint, ftWord:
Result := TValue.From<Integer>(AField.AsInteger);
ftLargeint:
Result := TValue.From<Int64>(AField.AsLargeInt);
ftFloat, ftCurrency, ftBCD:
Result := TValue.From<Double>(AField.AsFloat);
ftBoolean:
Result := TValue.From<Boolean>(AField.AsBoolean);
ftDate, ftDateTime, ftTimeStamp:
Result := TValue.From<TDateTime>(AField.AsDateTime);
ftBlob, ftBytes, ftVarBytes:
Result := TValue.From<TBytes>(AField.AsBytes);
else
Result := TValue.FromVariant(AField.Value);
end;
// Now, construct TNullable<T> using the implicit operator
// Assuming that TNullable<T> has an implicit operator from T
// This can be simulated by assigning the underlying value to a variable and then assigning that to TNullable<T>
// Create a dynamic variable of type TNullable<T>
NullableRttiType := FUnderlyingType.Context.FindType(TypeInfo(TNullable<>) );
// For simplicity, use TValue.From<T> to utilize the implicit operator
Result := TValue.FromVariant(Result.AsVariant);
end;
end.
Extensibility for Enumerations and Other Complex Types:
While not fully implemented in the example, the structure allows for easy extension to handle enumerations and other complex types by expanding type handling logic within the TNullableHandler or the main population methods.