function FormataInfo(info: Variant; tipo: TFormatType): string;
begin
// info := System.Variants.Null;
if VarIsNull(info) or VarIsEmpty(info) then
Exit(EmptyStr);
if VarType(info) = varUString then
begin
case tipo of
tiInteger: Exit(PegaInt(info).ToString);
tiMoney: Exit(FormatFloat(FMT_MONEY, GetMoney(info)));
tiFloat: Exit(FloatToStr(PegaFloat(info)));
tiDate: Exit(FormatDateTime('dd/mm/yyyy', PegaData(info)));
tiDateTime: Exit(FormatDateTime('dd/mm/yyyy hh:mm:ss', PegaDataHora(info)));
tiBoolean: Exit(IIF(info, 'S', 'N'));
tiByteArray: Exit(ByteArrayToHex(info));
tiNone: Exit(EmptyStr);
end;
end;
case tipo of
tiString: Result := VarToStr(info);
tiInteger: Result := IntToStr(Integer(info));
tiMoney: Result := FormatFloat(FMT_MONEY, Currency(info));
tiFloat: Result := FloatToStr(info);
tiBoolean: Result := string(IIF(Boolean(info), 'S', 'N'));
tiByteArray: Result := string(ByteArrayToHex(info));
tiDate:
begin
if VarType(info) in [varDate, varDouble] then
begin
if info = 0 then Exit(EmptyStr)
else if VarToDateTime(info) < EncodeDate(1900, 1, 1) then Exit(EmptyStr)
else Exit(FormatDateTime('dd/mm/yyyy', VarToDateTime(info)));
end
else
raise Exception.Create('FormataInfo: A informação [' + VarToStr(info) + '] não pode ser tratada como tiDate');
end;
tiDateTime:
begin
if VarType(info) in [varDate, varDouble] then
begin
if info = 0 then Exit(EmptyStr)
else Exit(FormatDateTime('dd/mm/yyyy hh:mm:ss', VarToDateTime(info)));
end
else
raise Exception.Create('FormataInfo: A informação [' + VarToStr(info) + '] não pode ser tratada como tiDateTime');
end;
tiNone: Result := EmptyStr;
else
raise Exception.Create('FormataInfo: o [' + GetEnumName(TypeInfo(TFormatType), Integer(tipo)) + '] não foi encontrado');
end;
end;
// Find the property by name
Prop := RttiType.GetProperty(FieldName);
if not Assigned(Prop) then
raise Exception.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;
// If still not found, determine default FmtType based on property type
if FmtType = tiNone then
begin
UnderlyingType := Prop.PropertyType;
// If the property is a TNullable<T>
if UnderlyingType.TypeKind = tkRecord then
begin
// Attempt to get the 'Value' field of TNullable<T>
ValueField := UnderlyingType.GetField('Value');
if Assigned(ValueField) then
begin
UnderlyingType := ValueField.FieldType;
end;
end;
case UnderlyingType.TypeKind of
tkInteger, tkInt64:
FmtType := tiInteger;
tkFloat:
begin
if UnderlyingType.Handle = TypeInfo(TDateTime) then
FmtType := tiDateTime
else
FmtType := tiFloat;
end;
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 := EmptyStr;
end
else
begin
// Not TNullable<T>, handle value directly
if not Value.IsEmpty then
Result := FormataInfo(Value.AsVariant, FmtType)
else
Result := EmptyStr;
end;
end
else
begin
// Not a record, handle value directly
if not Value.IsEmpty then
Result := FormataInfo(Value.AsVariant, FmtType)
else
Result := EmptyStr;
end;
destructor TQryRecInfo.Destroy;
begin
FDirtyFields.Free;
FPreviousValues.Free;
inherited;
end;
function GetPropNameAndField(Cls: TClass; PropIndex: integer; var PropName: string; var PropKind: TTypeKind): Boolean;
var
Ctx: TRttiContext;
Prop: TRttiProperty;
begin
PropName := '';
Ctx := TRttiContext.Create;
for Prop in Ctx.GetType(Cls).GetProperties do
begin
if (Prop as TRttiInstanceProperty).Index = PropIndex then
begin
PropName := Prop.Name;
PropKind := Prop.PropertyType.TypeKind;
Break;
end;
end;
Result := (PropName <> '');
end;
procedure TQryRecInfo.Set_Info(Index: integer; const Value: TValue);
var
PropName: string;
PropKind: TTypeKind;
Ctx: TRttiContext;
Field: TRttiField;
OldValue: TValue;
begin
if not GetPropNameAndField(Self.ClassType, Index, PropName, PropKind) then
raise Exception.Create('Error: The index "' + Index.ToString + '" does not exist in class "' + ClassType.ClassName + '"');
Ctx := TRttiContext.Create;
try
Field := Ctx.GetType(Self.ClassType).GetField('' + PropName);
if Assigned(Field) then
begin
// 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);
end
else
raise Exception.Create('Error: Field "' + PropName + '" not found.');
finally
// TRttiContext is a record; no need to free
end;
end;
procedure TQryRecInfo.Set_Info_NullableBoolean(Index: integer; const Value: TNullable);
begin
Set_Info(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableCurrency(Index: integer; const Value: TNullable);
begin
Set_Info(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableDateTime(Index: integer; const Value: TNullable);
begin
Set_Info(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableExtended(Index: integer; const Value: TNullable);
begin
Set_Info(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableInteger(Index: integer; const Value: TNullable);
begin
Set_Info(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableInt64(Index: integer; const Value: TNullable);
begin
Set_Info(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableString(Index: integer; const Value: TNullable);
begin
Set_Info(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.Set_Info_NullableVariant(Index: integer; const Value: TNullable);
begin
Set_Info(Index, TValue.From<TNullable>(Value));
end;
// Method to check if a field is dirty
function TQryRecInfo.IsFieldDirty(const FieldName: string): Boolean;
begin
Result := FDirtyFields.ContainsKey(FieldName);
end;
// Method to clear all dirty flags
procedure TQryRecInfo.ClearDirtyFlags;
begin
FDirtyFields.Clear;
end;
// Method to get the previous value of a property
function TQryRecInfo.GetPreviousValue(const FieldName: string): TValue;
begin
if FPreviousValues.TryGetValue(FieldName, Result) then
Exit;
// Return some default value or raise exception if not found
raise Exception.CreateFmt('No previous value found for field "%s".', [FieldName]);
end;
// Method to clear previous values
procedure TQryRecInfo.ClearPreviousValues;
begin
FPreviousValues.Clear;
end;
procedure TQryRecInfo.Fetch(DBConn: TUniConnection; QryTxt: string);
begin
if Assigned(DBConn) and (Trim(QryTxt) <> '') then
begin
var
qr:= TUniQuery.Create(nil);
qr.Connection:= DBConn;
qr.SQL.Text:= QryTxt;
qr.Open;
writeln(QryTxt); readln;
if qr.RecordCount > 0 then
begin
try
var Ctx: TRttiContext;
Ctx:= TRttiContext.Create;
var ObjType := Ctx.GetType(ClassType);
var Prop: TRttiProperty;
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then Continue;
var Field := qr.FindField(Prop.Name);
if not Assigned(Field) then Continue;
case Prop.PropertyType.TypeKind of
tkRecord:
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
begin
Ctx.GetType(ClassType).GetField('_' + Prop.Name).SetValue(Self, TValue.From<TNullable<string>>(Field.Value));
end;
end;
tkString, tkLString, tkWString, tkUString: Ctx.GetType(ClassType).GetField('_' + Prop.Name).SetValue(Pointer(Self), TValue.From<TNullable<string>>(Field.Value));
end;
end;
except
on E:Exception do
begin
writeln(E.Message);
readln;
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;
constructor PrimaryKeyAttribute.Create;
begin
inherited Create;
end;
{ FmtPropAttribute }
constructor FmtPropAttribute.Create(AFormatType: TFormatType);
begin
inherited Create;
FFormatType := AFormatType;
end;
end.
unit pixel_classes;
interface
uses
System.SysUtils, Rtti, TypInfo;
{$TYPEINFO ON}
type
TZString = type string;
type
TNullValue = record
end;
TNullable<T{: record}> = record
public
Value: T;
HasValue: Boolean;
class operator Implicit(const AValue: T): TNullable<T>;
class operator Implicit(const AValue: TNullable<T>): T;
class operator Implicit(const AValue: TNullValue): TNullable<T>;
class operator Explicit(const AValue: T): TNullable<T>;
// add these...
class operator Equal(const A: TNullable<T>; const B: TNullValue): Boolean;
class operator NotEqual(const A: TNullable<T>; const B: TNullValue): Boolean;
end;
var NullValue: TNullValue;
implementation
class operator TNullable.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;
end.
Carefully review the Delphi units above, then complete the TQryRecInfo.Fetch code for all the TNullable variations:
Certainly! To complete the TQryRecInfo.Fetch method for all the TNullable<T> variations (TNullable<string>, TNullable<Integer>, TNullable<Int64>, TNullable<Extended>, TNullable<Currency>, TNullable<TDateTime>, TNullable<Boolean>, and TNullable<Variant>), you need to handle each type explicitly within the method. This ensures that each nullable type is correctly instantiated and assigned based on the database field values.
Below is the updated Fetch method with comprehensive handling for all specified TNullable<T> variations:
procedure TQryRecInfo.Fetch(DBConn: TUniConnection; QryTxt: string);
begin
if Assigned(DBConn) and (Trim(QryTxt) <> '') then
begin
var
qr: TUniQuery;
qr := TUniQuery.Create(nil);
try
qr.Connection := DBConn;
qr.SpecificOptions.Values['FetchAll'] := 'True';
qr.SpecificOptions.Values['CreateConnection'] := 'False';
qr.SQL.Text := QryTxt;
qr.Open;
// Debugging lines removed for production
// writeln(QryTxt); readln;
if qr.RecordCount > 0 then
begin
try
var
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TUniField;
NullableValue: TValue;
FieldValue: Variant;
Ctx := TRttiContext.Create;
try
ObjType := Ctx.GetType(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;
FieldValue := Field.Value;
// Handle TNullable<T> types
if Prop.PropertyType.IsGenericType and
(Prop.PropertyType.GenericTypeType = gtRecord) and
(Prop.PropertyType.Name.StartsWith('TNullable<')) then
begin
if Prop.PropertyType.Name = 'TNullable<string>' then
begin
NullableValue := TValue.From<TNullable<string>>(FieldValue);
end
else if Prop.PropertyType.Name = 'TNullable<Integer>' then
begin
NullableValue := TValue.From<TNullable<Integer>>(FieldValue);
end
else if Prop.PropertyType.Name = 'TNullable<Int64>' then
begin
NullableValue := TValue.From<TNullable<Int64>>(FieldValue);
end
else if Prop.PropertyType.Name = 'TNullable<Extended>' then
begin
NullableValue := TValue.From<TNullable<Extended>>(FieldValue);
end
else if Prop.PropertyType.Name = 'TNullable<Currency>' then
begin
NullableValue := TValue.From<TNullable<Currency>>(FieldValue);
end
else if Prop.PropertyType.Name = 'TNullable<TDateTime>' then
begin
NullableValue := TValue.From<TNullable<TDateTime>>(FieldValue);
end
else if Prop.PropertyType.Name = 'TNullable<Boolean>' then
begin
NullableValue := TValue.From<TNullable<Boolean>>(FieldValue);
end
else if Prop.PropertyType.Name = 'TNullable<Variant>' then
begin
NullableValue := TValue.From<TNullable<Variant>>(FieldValue);
end
else
begin
// Unknown TNullable<T> type; skip or handle as needed
Continue;
end;
// Assign the nullable value to the corresponding field
ObjType.GetField('_' + Prop.Name).SetValue(Self, NullableValue);
end
else
begin
// Handle non-TNullable<T> types if necessary
case Prop.PropertyType.TypeKind of
tkString, tkLString, tkWString, tkUString:
begin
// Assuming these are not nullable; adjust as needed
ObjType.GetField('_' + Prop.Name).SetValue(Self, TValue.From<string>(FieldValue));
end;
tkInteger:
begin
ObjType.GetField('_' + Prop.Name).SetValue(Self, TValue.From<Integer>(FieldValue));
end;
tkInt64:
begin
ObjType.GetField('_' + Prop.Name).SetValue(Self, TValue.From<Int64>(FieldValue));
end;
tkFloat:
begin
if Prop.PropertyType.Handle = TypeInfo(TDateTime) then
ObjType.GetField('_' + Prop.Name).SetValue(Self, TValue.From<TDateTime>(FieldValue))
else
ObjType.GetField('_' + Prop.Name).SetValue(Self, TValue.From<Extended>(FieldValue));
end;
tkEnumeration:
begin
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
ObjType.GetField('_' + Prop.Name).SetValue(Self, TValue.From<Boolean>(FieldValue))
else
ObjType.GetField('_' + Prop.Name).SetValue(Self, TValue.From<Integer>(FieldValue)); // Adjust if needed
end;
tkVariant:
begin
ObjType.GetField('_' + Prop.Name).SetValue(Self, TValue.From<Variant>(FieldValue));
end;
else
begin
// Handle other types as needed
end;
end;
end;
end;
finally
// TRttiContext is a record; no need to free
end;
except
on E: Exception do
begin
writeln(E.Message);
readln;
end;
end;
end;
finally
qr.Free;
end;
end;
end;
Explanation of Changes
Handling Generic TNullable<T> Types:
Generic Type Check: The method first checks if the property type is a generic record starting with TNullable<.
Type-Specific Handling: For each TNullable<T> variation, it explicitly checks the type name and assigns the corresponding TValue.
Unknown Types: If an unknown TNullable<T> type is encountered, the code skips assignment. You can modify this behavior as needed (e.g., raise an exception or log a warning).
Non-Nullable Types:
For properties that are not of TNullable<T> types, the method handles them based on their TypeKind. You can expand this section if you have additional types to handle.
Field Naming Convention:
It's assumed that each property corresponds to a private field prefixed with an underscore (e.g., property Name corresponds to field _Name). Ensure that this naming convention is consistent across your classes.
Error Handling:
The method includes basic error handling that writes the exception message to the console. You may want to enhance this by integrating proper logging mechanisms depending on your application's requirements.
Cleanup:
The TUniQuery instance is properly freed in the finally block to prevent memory leaks.
Assumptions:
The code assumes that the database fields' names match the property names. If they don't, you might need to map them accordingly.
The Field.Value can be implicitly converted to the corresponding TNullable<T> type. Ensure that your database driver and field types support these conversions.
Further Enhancements
Dynamic Handling with RTTI:
If you have a large number of TNullable<T> types or anticipate adding more in the future, consider creating a mapping mechanism using RTTI to handle types dynamically. However, Delphi's RTTI for generics is somewhat limited, so explicit handling as shown above is often more straightforward.
Null Checks:
Depending on how your TNullable<T> records handle null values, you might need to implement additional logic to check for NULL or EMPTY database values before assignment.
Performance Considerations:
RTTI operations can be performance-intensive. If performance becomes a concern, consider optimizing the method by caching RTTI information or minimizing RTTI usage within loops.
Logging and Debugging:
Replace writeln and readln with proper logging mechanisms to better integrate with your application's logging infrastructure.
Final Notes
Ensure that all TNullable<T> types used in your properties are correctly defined and that their implicit conversions align with how database fields are retrieved. This implementation provides a robust foundation for fetching and assigning nullable types from a database query to your ORM classes.