Accepts a SQL SELECT query.
Executes the query using TUniQuery.
Uses RTTI to map query fields to class properties based on field names.
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.
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;
}
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;
Assistant
User
Implicit in an undeclared identifier. Review and fix it, making sure that the code is compilable on the latest Delphi versions
Assistant
User
'Implicit' keesp being an undeclared identifier
Assistant
User
error: Local procedure in generic method or method of generic type is not supported
Assistant
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;
published
property EmployeeID: TNullable index 0 read _EmployeeID write Set_Info_NullableInteger;
property DepartmentID: TNullable index 1 read _DepartmentID write Set_Info_NullableInteger;
property EmployeeName: TNullable index 2 read _EmployeeName write Set_Info_NullableString;
property ProjectID: TNullable index 3 read _ProjectID write Set_Info_NullableInteger;
property ProjectName: TNullable index 4 read _ProjectName write Set_Info_NullableString;
property ProjectBudget: TNullable index 5 read _ProjectBudget write Set_Info_NullableCurrency;
property ProjectDate: TNullable index 6 read _ProjectDate write Set_Info_NullableDateTime;
property ProjectStartMoment: TNullable index 7 read _ProjectStartMoment write Set_Info_NullableDateTime;
end;
implementation
end.
To implement a TQryRecInfoArray<T> class in Delphi that maps SQL query results to object properties using RTTI, we'll follow these steps:
Create a generic class TQryRecInfoArray<T>.
Map SQL fields to properties using RTTI.
Handle TNullable<> types and null values.
Show a usage example.
Here is the implementation:
delphi
unit QueryDataMapper;
interface
uses
System.SysUtils, System.Classes, System.Generics.Collections, System.Rtti,
Data.DB, Uni, pixel_classes;
type
TQryRecInfoArray<T: class, constructor> = class
private
FQuery: TUniQuery;
public
constructor Create(AQuery: TUniQuery);
function ExecuteAndMap: TObjectList<T>;
end;
implementation
uses
System.TypInfo;
constructor TQryRecInfoArray<T>.Create(AQuery: TUniQuery);
begin
inherited Create;
FQuery := AQuery;
end;
function TQryRecInfoArray<T>.ExecuteAndMap: TObjectList<T>;
var
Context: TRttiContext;
RttiType: TRttiType;
Prop: TRttiProperty;
Field: TField;
Obj: T;
begin
Result := TObjectList<T>.Create(True);
Context := TRttiContext.Create;
RttiType := Context.GetType(T);
FQuery.Open;
try
while not FQuery.Eof do
begin
Obj := T.Create;
for Field in FQuery.Fields do
begin
Prop := RttiType.GetProperty(Field.FieldName);
if Assigned(Prop) and Prop.IsWritable then
begin
if Prop.PropertyType.TypeKind = tkRecord then
begin
var TValue: TValue;
case Field.DataType of
ftInteger, ftSmallint, ftWord:
TValue := TNullable<Integer>.Implicit(Field.AsInteger);
ftFloat, ftCurrency, ftBCD:
TValue := TNullable<Currency>.Implicit(Field.AsCurrency);
ftDate, ftTime, ftDateTime:
TValue := TNullable<TDateTime>.Implicit(Field.AsDateTime);
ftString, ftWideString:
TValue := TNullable<String>.Implicit(Field.AsString);
else
TValue := TValue.Empty; // add more cases as needed
end;
if (Field.IsNull) then
TValue := TNullable<Integer>.Implicit(NullValue);
Prop.SetValue(TObject(Obj), TValue);
end
else
begin
Prop.SetValue(TObject(Obj), Field.Value);
end;
end;
end;
Result.Add(Obj);
FQuery.Next;
end;
finally
FQuery.Close;
end;
end;
end.
Usage Example:
delphi
uses
QueryDataMapper, Uni, formgerenc_Classes, System.Generics.Collections;
procedure PopulateEmployeeProjectList;
var
UniQuery: TUniQuery;
EmployeeProjects: TObjectList<TEmployeeProject>;
begin
UniQuery := TUniQuery.Create(nil);
try
UniQuery.Connection := YourUniConnection; // Assign your database connection
UniQuery.SQL.Text := 'SELECT * FROM EmployeeProjects'; // Your SQL query
EmployeeProjects := TQryRecInfoArray<TEmployeeProject>.Create(UniQuery).ExecuteAndMap;
try
for var EmpProj in EmployeeProjects do
begin
// Process each TEmployeeProject instance
// E.g., ShowMessage(IntToStr(EmpProj.EmployeeID))
end;
finally
EmployeeProjects.Free;
end;
finally
UniQuery.Free;
end;
end;
Explanation:
TQryRecInfoArray<T> Class: This is a generic class where T must be a class with a parameterless constructor.
RTTI Mapping: We use RTTI to dynamically map SQL query results from TUniQuery fields to the properties of class T.
Handling TNullable<>: We check if a field is null; if so, we assign the NullValue to the TNullable<> property.
Usage Example: Shows how to execute a query and map the results to a list of TEmployeeProject instances.
This implementation is flexible, assuming the field names in the SQL query match the object properties. You may need to customize data type handling depending on your specific requirements.
To resolve the issue with the use of implicit operators in Delphi, which might cause compilation errors due to undeclared identifiers or implicit operator issues, the key is to explicitly handle TNullable values within the TQryRecInfoArray<T> implementation. Let's correct the implementation:
Corrected Implementation
delphi
unit QueryDataMapper;
interface
uses
System.SysUtils, System.Generics.Collections, System.Rtti, Data.DB, Uni,
pixel_classes;
type
TQryRecInfoArray<T: class, constructor> = class
private
FQuery: TUniQuery;
public
constructor Create(AQuery: TUniQuery);
function ExecuteAndMap: TObjectList<T>;
end;
implementation
constructor TQryRecInfoArray<T>.Create(AQuery: TUniQuery);
begin
inherited Create;
FQuery := AQuery;
end;
function TQryRecInfoArray<T>.ExecuteAndMap: TObjectList<T>;
var
Context: TRttiContext;
RttiType: TRttiType;
Prop: TRttiProperty;
Field: TField;
Obj: T;
// Helper function to handle TNullable assignment
procedure SetNullableValue(const Prop: TRttiProperty; const Obj: TObject; const Value: TValue; const IsNull: Boolean);
begin
if IsNull then
Prop.SetValue(Obj, TValue.From(TNullable<Integer>.Implicit(NullValue))) // Using Integer as a placeholder type
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Integer>) then
Prop.SetValue(Obj, TValue.From(TNullable<Integer>.Implicit(Value.AsInteger)))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<String>) then
Prop.SetValue(Obj, TValue.From(TNullable<String>.Implicit(Value.AsString)))
else if Prop.PropertyType.Handle = TypeInfo(TNullable<TDateTime>) then
Prop.SetValue(Obj, TValue.From(TNullable<TDateTime>.Implicit(Value.AsExtended))) // Handle as Extended or use AsType<TDateTime>
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Currency>) then
Prop.SetValue(Obj, TValue.From(TNullable<Currency>.Explicit(Value.AsCurrency)));
end;
begin
Result := TObjectList<T>.Create(True);
Context := TRttiContext.Create;
RttiType := Context.GetType(T);
FQuery.Open;
try
while not FQuery.Eof do
begin
Obj := T.Create;
for Field in FQuery.Fields do
begin
Prop := RttiType.GetProperty(Field.FieldName);
if Assigned(Prop) and Prop.IsWritable then
begin
if Prop.PropertyType.TypeKind = tkRecord then
begin
// Explicit handling for TNullable<> fields
SetNullableValue(Prop, TObject(Obj), Field.Value, Field.IsNull);
end
else
begin
Prop.SetValue(TObject(Obj), Field.Value);
end;
end;
end;
Result.Add(Obj);
FQuery.Next;
end;
finally
FQuery.Close;
end;
end;
end.
Key Adjustments:
SetNullableValue Procedure: Handles TNullable<> assignments, including null checks to ensure proper handling of null SQLite values. The procedure sets the appropriate property depending on its type.
Explicit Type Checks: The procedure explicitly checks the property type before casting the value to TNullable<>. This ensures type safety, and NullValue is used to represent null assignments.
Compile-Time Consistency: Removed implicit operator usage and ensured explicit handling of different data types.
Usage Example:
Consider using the same usage example as in the earlier code for testing, making sure to have the corresponding database access components configured properly before executing the code. This will allow successful compilation and execution when run in a Delphi environment. Adjust the database components such as YourUniConnection and SQL query, as necessary, for your specific use case.
If you encounter issues with the implicit keyword being recognized as an undeclared identifier, this is likely because Delphi does not natively support custom implicit conversion operators on record types as languages like C# do. To address this, we need to manually handle conversions to and from TNullable<T>. Below, I'll provide a refactored version of the TNullable<T> usage in a Delphi-friendly way:
Key Approaches:
Manual Assignment Handling: Instead of relying on implicit conversions, manually check the field's nullability and assign values accordingly.
Utility Functions: Define utility functions to assist in managing TNullable<T> values.
Corrected Implementation
Let's refine your implementation to avoid reliance on implicit conversions:
delphi
unit QueryDataMapper;
interface
uses
System.SysUtils, System.Generics.Collections, System.Rtti, Data.DB, Uni,
pixel_classes;
type
TQryRecInfoArray<T: class, constructor> = class
private
FQuery: TUniQuery;
public
constructor Create(AQuery: TUniQuery);
function ExecuteAndMap: TObjectList<T>;
end;
implementation
constructor TQryRecInfoArray<T>.Create(AQuery: TUniQuery);
begin
inherited Create;
FQuery := AQuery;
end;
function TQryRecInfoArray<T>.ExecuteAndMap: TObjectList<T>;
var
Context: TRttiContext;
RttiType: TRttiType;
Prop: TRttiProperty;
Field: TField;
Obj: T;
// Helper function to handle TNullable assignment
procedure SetNullableValue<TProp>(const Prop: TRttiProperty; const Obj: TObject; const Value: TProp; const IsNull: Boolean);
var
NullableValue: TNullable<TProp>;
begin
if IsNull then
NullableValue := NullValue
else
begin
NullableValue.Value := Value;
NullableValue.HasValue := True;
end;
Prop.SetValue(Obj, TValue.From<TNullable<TProp>>(NullableValue));
end;
begin
Result := TObjectList<T>.Create(True);
Context := TRttiContext.Create;
RttiType := Context.GetType(T);
FQuery.Open;
try
while not FQuery.Eof do
begin
Obj := T.Create;
for Field in FQuery.Fields do
begin
Prop := RttiType.GetProperty(Field.FieldName);
if Assigned(Prop) and Prop.IsWritable then
begin
if Prop.PropertyType.Handle = TypeInfo(TNullable<Integer>) then
SetNullableValue(Prop, TObject(Obj), Field.AsInteger, Field.IsNull)
else if Prop.PropertyType.Handle = TypeInfo(TNullable<String>) then
SetNullableValue(Prop, TObject(Obj), Field.AsString, Field.IsNull)
else if Prop.PropertyType.Handle = TypeInfo(TNullable<TDateTime>) then
SetNullableValue(Prop, TObject(Obj), Field.AsDateTime, Field.IsNull)
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Currency>) then
SetNullableValue(Prop, TObject(Obj), Field.AsCurrency, Field.IsNull)
else
Prop.SetValue(TObject(Obj), Field.Value); // direct assignment for non-nullable types
end;
end;
Result.Add(Obj);
FQuery.Next;
end;
finally
FQuery.Close;
end;
end;
end.
Key Adjustments:
SetNullableValue Procedure: Manages nullable field assignments without using implicit operations by explicitly checking if a field is null and then preparing a TNullable instance.
Explicit Type Handling: For each type supported, explicitly set Value and HasValue fields of TNullable<T>.
Manual Null Handling: If a field is null, use NullValue to indicate that the value has no data (assigns HasValue as False).
Usage Example:
The usage example remains largely the same as before, just ensure that your database connection and query logic are set up accordingly.
This approach avoids implicit operators and manually handles nullable type logic, ensuring compatibility across Delphi versions.
In Delphi, local procedures in generic methods or methods of generic types are indeed not permitted, which explains the error you're encountering. To solve this, you can move the local helper procedure SetNullableValue to a separate procedure or a nested function outside of the method. This also involves passing any required parameters that the procedure needs to operate on.
Here's how you can refactor the code to avoid the issue:
Refactored Implementation
First, we create a utility function outside of the generic method to handle assigning TNullable values:
delphi
unit QueryDataMapper;
interface
uses
System.SysUtils, System.Generics.Collections, System.Rtti, Data.DB, Uni,
pixel_classes;
type
// Utility functions to handle TNullable assignments
procedure SetNullableInteger(Prop: TRttiProperty; Obj: TObject; Field: TField);
procedure SetNullableString(Prop: TRttiProperty; Obj: TObject; Field: TField);
procedure SetNullableDateTime(Prop: TRttiProperty; Obj: TObject; Field: TField);
procedure SetNullableCurrency(Prop: TRttiProperty; Obj: TObject; Field: TField);
TQryRecInfoArray<T: class, constructor> = class
private
FQuery: TUniQuery;
public
constructor Create(AQuery: TUniQuery);
function ExecuteAndMap: TObjectList<T>;
end;
implementation
procedure SetNullableInteger(Prop: TRttiProperty; Obj: TObject; Field: TField);
var
NullableValue: TNullable<Integer>;
begin
if Field.IsNull then
NullableValue := NullValue
else
begin
NullableValue.Value := Field.AsInteger;
NullableValue.HasValue := True;
end;
Prop.SetValue(Obj, TValue.From<TNullable<Integer>>(NullableValue));
end;
procedure SetNullableString(Prop: TRttiProperty; Obj: TObject; Field: TField);
var
NullableValue: TNullable<String>;
begin
if Field.IsNull then
NullableValue := NullValue
else
begin
NullableValue.Value := Field.AsString;
NullableValue.HasValue := True;
end;
Prop.SetValue(Obj, TValue.From<TNullable<String>>(NullableValue));
end;
procedure SetNullableDateTime(Prop: TRttiProperty; Obj: TObject; Field: TField);
var
NullableValue: TNullable<TDateTime>;
begin
if Field.IsNull then
NullableValue := NullValue
else
begin
NullableValue.Value := Field.AsDateTime;
NullableValue.HasValue := True;
end;
Prop.SetValue(Obj, TValue.From<TNullable<TDateTime>>(NullableValue));
end;
procedure SetNullableCurrency(Prop: TRttiProperty; Obj: TObject; Field: TField);
var
NullableValue: TNullable<Currency>;
begin
if Field.IsNull then
NullableValue := NullValue
else
begin
NullableValue.Value := Field.AsCurrency;
NullableValue.HasValue := True;
end;
Prop.SetValue(Obj, TValue.From<TNullable<Currency>>(NullableValue));
end;
constructor TQryRecInfoArray<T>.Create(AQuery: TUniQuery);
begin
inherited Create;
FQuery := AQuery;
end;
function TQryRecInfoArray<T>.ExecuteAndMap: TObjectList<T>;
var
Context: TRttiContext;
RttiType: TRttiType;
Prop: TRttiProperty;
Field: TField;
Obj: T;
begin
Result := TObjectList<T>.Create(True);
Context := TRttiContext.Create;
RttiType := Context.GetType(T);
FQuery.Open;
try
while not FQuery.Eof do
begin
Obj := T.Create;
for Field in FQuery.Fields do
begin
Prop := RttiType.GetProperty(Field.FieldName);
if Assigned(Prop) and Prop.IsWritable then
begin
// Using separate procedures for each nullable type handling
if Prop.PropertyType.Handle = TypeInfo(TNullable<Integer>) then
SetNullableInteger(Prop, TObject(Obj), Field)
else if Prop.PropertyType.Handle = TypeInfo(TNullable<String>) then
SetNullableString(Prop, TObject(Obj), Field)
else if Prop.PropertyType.Handle = TypeInfo(TNullable<TDateTime>) then
SetNullableDateTime(Prop, TObject(Obj), Field)
else if Prop.PropertyType.Handle = TypeInfo(TNullable<Currency>) then
SetNullableCurrency(Prop, TObject(Obj), Field)
else
Prop.SetValue(TObject(Obj), Field.Value); // direct assignment for non-nullable types
end;
end;
Result.Add(Obj);
FQuery.Next;
end;
finally
FQuery.Close;
end;
end;
end.
Explanation:
Separate Procedures: Moved each type of TNullable assignment to separate global procedures (SetNullableInteger, SetNullableString, etc.) that take in the TRttiProperty, TObject, and TField as parameters.
Manual Handling: Each of these procedures checks if the field is null and assigns a NullValue or a valid value accordingly to the TNullable type.
Simplified ExecuteAndMap: The method ExecuteAndMap now simply calls the appropriate procedure for each type supported based on the field's type information.
By using this approach, you can ensure that your application compiles and runs correctly in environments where local procedures in generic contexts are not supported.