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.
Implementation Steps
Define the Generic TQryRecArray<T> Class.
Implement the Fetch Method 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;
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;
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);
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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;
///
/// Represents information about a table used in the SQL query.
///
TTableInfo = class
private
FSchemaName: string;
FTableName: string;
FAlias: string;
public
///
/// Schema name of the table.
///
property SchemaName: string read FSchemaName write FSchemaName;
/// <summary>
/// Name of the table.
/// </summary>
property TableName: string read FTableName write FTableName;
/// <summary>
/// Alias of the table as defined in the query.
/// </summary>
property Alias: string read FAlias write FAlias;
end;
///
/// Parses SQL SELECT statements to extract table and column information.
///
TSQLParser = class
private
FSQLText: string;
FTables: TObjectList;
FColumns: TObjectList;
FConnection: TUniConnection;
FPrimaryKeys: TDictionary<string, TList>;
FTableColumns: TDictionary<string, TList>; // Cache for table columns
procedure Parse;
procedure ParseFromClause;
procedure ParseSelectClause;
function SplitSelectColumns(const SelectClause: string): TArray<string>;
function IsExpression(const S: string): Boolean;
function IsClauseKeyword(const Token: string): Boolean;
function GetTableInfoByAliasOrName(const AliasOrName: string): TTableInfo;
function IsJoinType(const Token: string): Boolean;
procedure CheckPrimaryKeys; // Checks if columns are primary keys
procedure FillPrimaryKeyDictionary; // Fills the primary key dictionary
function GetTableColumnNames(const SchemaName, TableName: string): TList<string>; // Get column names for a table
function IsReservedWord(const Token: string; const ReservedWords: array of string): Boolean;
public
procedure AssignDataTypesToColumns;
///
/// Initializes a new instance of the TSQLParser class.
///
/// The SQL query text to parse.
/// The database connection used to retrieve schema information.
constructor Create(const SQLText: string; AConnection: TUniConnection);
///
/// Frees all resources used by the TSQLParser instance.
///
destructor Destroy; override;
/// <summary>
/// Gets the list of tables parsed from the SQL query.
/// </summary>
property Tables: TObjectList<TTableInfo> read FTables;
/// <summary>
/// Gets the list of columns parsed from the SQL query.
/// </summary>
property Columns: TObjectList<TColumnInfo> read FColumns;
end;
implementation
{ TSQLParser }
constructor TSQLParser.Create(const SQLText: string; AConnection: TUniConnection);
begin
inherited Create;
FSQLText := SQLText;
FConnection := AConnection; // Store the provided database connection
FTables := TObjectList.Create(True); // Owns objects
FColumns := TObjectList.Create(True); // Owns objects
FPrimaryKeys := TDictionary<string, TList>.Create;
FTableColumns := TDictionary<string, TList>.Create;
Parse;
FillPrimaryKeyDictionary; // After parsing, fill the primary key dictionary
CheckPrimaryKeys; // Then check for primary key columns using the cache
AssignDataTypesToColumns; // Assign data types to columns
end;
destructor TSQLParser.Destroy;
var
ColumnsList: TList;
begin
// Free the lists inside the dictionaries
for ColumnsList in FPrimaryKeys.Values do
ColumnsList.Free;
FPrimaryKeys.Free;
for ColumnsList in FTableColumns.Values do
ColumnsList.Free;
FTableColumns.Free;
FTables.Free;
FColumns.Free;
inherited;
end;
procedure TSQLParser.Parse;
begin
ParseFromClause;
ParseSelectClause;
end;
procedure TSQLParser.AssignDataTypesToColumns;
var
Query: TUniQuery;
Field: TField;
ColumnInfo: TColumnInfo;
FieldName: string;
begin
Query := TUniQuery.Create(nil);
try
Query.Connection := FConnection;
Query.SQL.Text := FSQLText;
try
Query.Open;
// Iterate over fields to get field types
for Field in Query.Fields do
begin
FieldName := Field.FieldName;
// Try to find matching ColumnInfo by QueryColumnAlias or FullName
for ColumnInfo in FColumns do
begin
if SameText(ColumnInfo.QueryColumnAlias, FieldName) or
SameText(ColumnInfo.FullName, FieldName) or
SameText(ColumnInfo.ReferencedTableColumn, FieldName) then
begin
ColumnInfo.DataType := Field.DataType;
Break;
end;
end;
end;
Query.Close;
except
on E: Exception do
begin
// Handle exception, e.g., log error message
// Optionally set DataType to ftUnknown for all columns
for ColumnInfo in FColumns do
ColumnInfo.DataType := ftUnknown;
end;
end;
finally
Query.Free;
end;
end;
function TSQLParser.IsClauseKeyword(const Token: string): Boolean;
const
ClauseKeywords: array[0..10] of string = (
'WHERE', 'GROUP BY', 'HAVING', 'ORDER BY', 'LIMIT',
'OFFSET', 'UNION', 'INTERSECT', 'EXCEPT', 'EXISTS', ';'
);
var
Keyword: string;
begin
Result := False;
for Keyword in ClauseKeywords do
begin
if SameText(Token, Keyword) then
Exit(True);
end;
end;
procedure TSQLParser.ParseFromClause;
var
FromMatch, NextClauseMatch: TMatch;
FromPos, NextClausePos: Integer;
FromClause: string;
Tokens: TArray;
i: Integer;
Token: string;
TableInfo: TTableInfo;
NextToken: string;
RemainingText: string;
begin
// Find position of FROM
FromMatch := TRegEx.Match(FSQLText, '\bFROM\b', [roIgnoreCase]);
if not FromMatch.Success then Exit; // No FROM clause found
FromPos := FromMatch.Index + FromMatch.Length;
// Extract the text after FROM
RemainingText := Copy(FSQLText, FromPos + 1, MaxInt).Trim;
// Find position of the next clause (e.g., WHERE, GROUP BY, etc.) in RemainingText
NextClauseMatch := TRegEx.Match(RemainingText, '\b(WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT|EXISTS|;)\b', [roIgnoreCase]);
if NextClauseMatch.Success then
NextClausePos := NextClauseMatch.Index
else
NextClausePos := Length(RemainingText) + 1; // No next clause found
// Split the FROM clause into tokens using spaces and commas, considering possible quoted identifiers
Tokens := TRegEx.Split(FromClause, '\s+|,(?![^()]*))'); // Split on spaces or commas not within parentheses
i := 0;
while i < Length(Tokens) do
begin
Token := Trim(Tokens[i]);
if Token = '' then
begin
Inc(i);
Continue;
end;
if IsJoinType(Token) or SameText(Token, 'JOIN') then
begin
// Skip join type and 'JOIN' keyword
Inc(i);
Continue;
end
else if SameText(Token, 'ON') then
begin
// Skip tokens until the next 'JOIN' or clause keyword
Inc(i);
while (i < Length(Tokens)) and not (IsJoinType(Tokens[i]) or SameText(Tokens[i], 'JOIN') or IsClauseKeyword(Tokens[i])) do
Inc(i);
Continue;
end
else if SameText(Token, 'USING') then
begin
// Skip tokens within 'USING (...)'
Inc(i);
while (i < Length(Tokens)) and not (Tokens[i].Contains(')')) do
Inc(i);
Inc(i); // Skip the token with ')'
Continue;
end
else
begin
// Process table name (may include schema)
TableInfo := TTableInfo.Create;
// Check for schema.table format, considering possible quoted identifiers
if Pos('.', Token) > 0 then
begin
var DotPos := LastDelimiter('.', Token);
TableInfo.SchemaName := Copy(Token, 1, DotPos - 1).Trim(['"', '`']);
TableInfo.TableName := Copy(Token, DotPos + 1, Length(Token)).Trim(['"', '`']);
end
else
begin
TableInfo.SchemaName := FConnection.Database; // Assume default schema
TableInfo.TableName := Token.Trim(['"', '`']);
end;
// Check for alias
if (i + 1) < Length(Tokens) then
begin
NextToken := Tokens[i + 1];
if SameText(NextToken, 'AS') then
begin
// Alias after 'AS' keyword
if (i + 2) < Length(Tokens) then
begin
TableInfo.Alias := Tokens[i + 2].Trim(['"', '`']);
i := i + 2; // skip 'AS' and the alias
end
else
begin
// 'AS' without alias - skip 'AS'
i := i + 1;
end;
end
else if not (IsJoinType(NextToken) or SameText(NextToken, 'JOIN') or SameText(NextToken, 'ON')
or SameText(NextToken, 'USING') or IsClauseKeyword(NextToken)) then
begin
// Alias without 'AS'
TableInfo.Alias := NextToken.Trim(['"', '`']);
Inc(i); // move to the alias
end;
end;
FTables.Add(TableInfo);
Inc(i); // move to the next token after processing
end;
end;
end;
function TSQLParser.SplitSelectColumns(const SelectClause: string): TArray;
var
i: Integer;
c: Char;
InSingleQuote, InDoubleQuote: Boolean;
ParenthesisDepth: Integer;
CurrentColumn: string;
ColumnsList: TList;
begin
InSingleQuote := False;
InDoubleQuote := False;
ParenthesisDepth := 0;
CurrentColumn := '';
ColumnsList := TList.Create;
try
i := 1;
while i <= Length(SelectClause) do
begin
c := SelectClause[i];
if (c = '''') and not InDoubleQuote then
begin
InSingleQuote := not InSingleQuote;
CurrentColumn := CurrentColumn + c;
end
else if (c = '"') and not InSingleQuote then
begin
InDoubleQuote := not InDoubleQuote;
CurrentColumn := CurrentColumn + c;
end
else if not InSingleQuote and not InDoubleQuote then
begin
if c = '(' then
begin
Inc(ParenthesisDepth);
CurrentColumn := CurrentColumn + c;
end
else if c = ')' then
begin
Dec(ParenthesisDepth);
CurrentColumn := CurrentColumn + c;
end
else if (c = ',') and (ParenthesisDepth = 0) then
begin
// Column separator
ColumnsList.Add(Trim(CurrentColumn));
CurrentColumn := '';
end
else
begin
CurrentColumn := CurrentColumn + c;
end
end
else
begin
// Inside quotes
CurrentColumn := CurrentColumn + c;
end;
Inc(i);
end;
// After the loop, add the last column
if CurrentColumn.Trim <> '' then
ColumnsList.Add(Trim(CurrentColumn));
Result := ColumnsList.ToArray;
finally
ColumnsList.Free;
end;
end;
procedure TSQLParser.ParseSelectClause;
var
SelectMatch, FromMatch: TMatch;
SelectClause: string;
ColumnsStr: string;
ColumnList: TArray;
ColumnStr: string;
ColumnInfo: TColumnInfo;
Regex: TRegEx;
Match: TMatch;
TableAliasOrName: string;
ColumnName: string;
TableInfo: TTableInfo;
ReservedWords: array of string;
Tokens: TArray;
i: Integer;
SelectPos, FromPos: Integer;
SelectLength: Integer;
begin
// Find position of SELECT and FROM
SelectMatch := TRegEx.Match(FSQLText, '\bSELECT\b', [roIgnoreCase]);
FromMatch := TRegEx.Match(FSQLText, '\bFROM\b', [roIgnoreCase]);
if (not SelectMatch.Success) or (not FromMatch.Success) then Exit;
// Extract the SELECT clause content
SelectLength := FromPos - SelectPos;
if SelectLength <= 0 then Exit;
SelectClause := Copy(FSQLText, SelectPos + 1, SelectLength - 1).Trim;
// List of reserved words that may appear after SELECT
ReservedWords := ['ALL', 'DISTINCT', 'DISTINCTROW', 'HIGH_PRIORITY', 'STRAIGHT_JOIN',
'SQL_SMALL_RESULT', 'SQL_BIG_RESULT', 'SQL_BUFFER_RESULT', 'SQL_CACHE',
'SQL_NO_CACHE', 'SQL_CALC_FOUND_ROWS'];
// Split the SelectClause into tokens to check for reserved words at the beginning
Tokens := TRegEx.Split(SelectClause, '\s+');
i := 0;
// Skip reserved words at the beginning
while (i < Length(Tokens)) and IsReservedWord(Tokens[i], ReservedWords) do
begin
Inc(i);
end;
// Reconstruct ColumnsStr without leading reserved words
if i >= Length(Tokens) then
ColumnsStr := ''
else
ColumnsStr := String.Join(' ', Copy(Tokens, i, Length(Tokens) - i));
if ColumnsStr.IsEmpty then Exit;
// Use the new SplitSelectColumns function to split columns
ColumnList := SplitSelectColumns(ColumnsStr);
for i := 0 to Length(ColumnList) - 1 do
begin
ColumnStr := Trim(ColumnList[i]);
// Regular expression to extract column expressions and aliases
// Handles cases like "expression AS alias", "expression alias", or just "expression"
Regex := TRegEx.Create('^(.*?)(?:\s+(?:AS\s+)?(\w+))?$', [roIgnoreCase]);
Match := Regex.Match(ColumnStr);
ColumnInfo := TColumnInfo.Create; // Create the ColumnInfo object
if Match.Success then
begin
ColumnInfo.FullName := Match.Groups[1].Value.Trim;
if Match.Groups.Count > 2 then
ColumnInfo.QueryColumnAlias := Match.Groups[2].Value.Trim
else
ColumnInfo.QueryColumnAlias := '';
end
else
begin
ColumnInfo.FullName := ColumnStr;
ColumnInfo.QueryColumnAlias := '';
end;
// Determine if the column is an expression
if IsExpression(ColumnInfo.FullName) then
begin
// It's an expression
ColumnInfo.RealSchemaName := '[none]';
ColumnInfo.RealTableName := '[none]';
ColumnInfo.ReferencedTableColumn := '[none]';
end
else
begin
// It's a simple column reference
if ColumnInfo.FullName.Contains('.') then
begin
// Parse table alias/name and column name
var DotPos := LastDelimiter('.', ColumnInfo.FullName);
TableAliasOrName := Copy(ColumnInfo.FullName, 1, DotPos - 1).Trim(['"', '`']);
ColumnName := Copy(ColumnInfo.FullName, DotPos + 1, Length(ColumnInfo.FullName)).Trim(['"', '`']);
// Get the table info for this alias or name
TableInfo := GetTableInfoByAliasOrName(TableAliasOrName);
if Assigned(TableInfo) then
begin
ColumnInfo.RealSchemaName := TableInfo.SchemaName;
ColumnInfo.RealTableName := TableInfo.TableName;
end
else
begin
// Table alias/name not found; mark as unknown
ColumnInfo.RealSchemaName := '[unknown schema]';
ColumnInfo.RealTableName := '[unknown table]';
end;
ColumnInfo.ReferencedTableColumn := ColumnName;
end
else
begin
// Column without table alias/name prefix
ColumnInfo.ReferencedTableColumn := ColumnInfo.FullName.Trim(['"', '`']);
ColumnInfo.RealTableName := '';
ColumnInfo.RealSchemaName := '';
if FTables.Count = 1 then
begin
// Assign the only table's name
ColumnInfo.RealTableName := FTables[0].TableName;
ColumnInfo.RealSchemaName := FTables[0].SchemaName;
end
else if FTables.Count > 1 then
begin
// More than one table: try to find the table(s) that contain this column
var PossibleTables := TList<TTableInfo>.Create;
try
for var TInfo in FTables do
begin
var ColumnsList := GetTableColumnNames(TInfo.SchemaName, TInfo.TableName);
if ColumnsList.Contains(LowerCase(ColumnInfo.ReferencedTableColumn)) then
PossibleTables.Add(TInfo);
end;
if PossibleTables.Count = 1 then
begin
// Only one table contains the column, assign it
ColumnInfo.RealTableName := PossibleTables[0].TableName;
ColumnInfo.RealSchemaName := PossibleTables[0].SchemaName;
end
else if PossibleTables.Count > 1 then
begin
// Column is ambiguous - exists in multiple tables
ColumnInfo.RealTableName := '[ambiguous]';
ColumnInfo.RealSchemaName := '[ambiguous schema]';
end
else
begin
// Column doesn't exist in any known table
ColumnInfo.RealTableName := '[unknown]';
ColumnInfo.RealSchemaName := '[unknown schema]';
end;
finally
PossibleTables.Free;
end;
end
else
begin
// No table information available
ColumnInfo.RealTableName := '[no tables parsed]';
ColumnInfo.RealSchemaName := '[no tables parsed]';
end;
end;
end;
FColumns.Add(ColumnInfo);
end;
end;
function TSQLParser.IsReservedWord(const Token: string; const ReservedWords: array of string): Boolean;
var
Word: string;
begin
for Word in ReservedWords do
begin
if SameText(Token, Word) then
Exit(True);
end;
Result := False;
end;
function TSQLParser.IsExpression(const S: string): Boolean;
var
Value: string;
ReservedFunctions: array of string;
begin
Value := Trim(S);
// Check for string literal (enclosed in single quotes)
if (Value.StartsWith('''') and Value.EndsWith('''')) then
Exit(True);
// Check for string literal (enclosed in double quotes)
if (Value.StartsWith('"') and Value.EndsWith('"')) then
Exit(True);
// Check for numeric literal
if TRegEx.IsMatch(Value, '^-?\d+(.\d+)?$') then
Exit(True);
if IsReservedWord(Value, ReservedFunctions) then
Exit(True);
// Existing heuristic for expressions involving operators or parentheses
Result := Value.Contains('(') or
Value.Contains('+') or
Value.Contains('-') or
Value.Contains('*') or
Value.Contains('/') or
(Value.Contains(' ') and not Value.Contains('.'));
end;
function TSQLParser.GetTableInfoByAliasOrName(const AliasOrName: string): TTableInfo;
var
TableInfo: TTableInfo;
begin
Result := nil;
for TableInfo in FTables do
begin
if SameText(TableInfo.Alias, AliasOrName) then
Exit(TableInfo)
else if (TableInfo.Alias.IsEmpty) and SameText(TableInfo.TableName, AliasOrName) then
Exit(TableInfo);
end;
end;
function TSQLParser.GetTableColumnNames(const SchemaName, TableName: string): TList;
var
ColumnsList: TList;
Query: TUniQuery;
ColumnName: string;
Key: string;
begin
Key := LowerCase(SchemaName + '.' + TableName);
if FTableColumns.TryGetValue(Key, ColumnsList) then
begin
Result := ColumnsList;
Exit;
end;
while not Query.Eof do
begin
ColumnName := LowerCase(Query.FieldByName('COLUMN_NAME').AsString);
ColumnsList.Add(ColumnName);
Query.Next;
end;
Query.Close;
finally
Query.Free;
end;
FTableColumns.Add(Key, ColumnsList);
Result := ColumnsList;
except
ColumnsList.Free;
raise;
end;
end;
function TSQLParser.IsJoinType(const Token: string): Boolean;
const
JoinTypes: array[0..7] of string = ('JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL', 'CROSS', 'NATURAL', 'OUTER');
var
JoinType: string;
begin
Result := False;
if Token.IsEmpty then Exit;
for JoinType in JoinTypes do
begin
if SameText(Token, JoinType) then
Exit(True);
end;
end;
procedure TSQLParser.FillPrimaryKeyDictionary;
var
Query: TUniQuery;
TableName, ColumnName, SchemaName: string;
ColumnsList: TList;
begin
if not Assigned(FConnection) then
Exit; // Cannot fill without a database connection
Query := TUniQuery.Create(nil);
try
Query.Connection := FConnection;
// Use the schema name from the connection if not specified
SchemaName := FConnection.Database;
Query.SQL.Text :=
'SELECT TABLE_NAME, COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE ' +
'WHERE TABLE_SCHEMA = :SchemaName AND CONSTRAINT_NAME = ''PRIMARY'' ' +
'ORDER BY TABLE_NAME, ORDINAL_POSITION';
Query.ParamByName('SchemaName').AsString := SchemaName;
Query.Open;
while not Query.Eof do
begin
TableName := LowerCase(Query.FieldByName('TABLE_NAME').AsString);
ColumnName := LowerCase(Query.FieldByName('COLUMN_NAME').AsString);
if not FPrimaryKeys.TryGetValue(TableName, ColumnsList) then
begin
ColumnsList := TList<string>.Create;
FPrimaryKeys.Add(TableName, ColumnsList);
end;
ColumnsList.Add(ColumnName);
Query.Next;
end;
Query.Close;
finally
Query.Free;
end;
end;
procedure TSQLParser.CheckPrimaryKeys;
var
ColumnInfo: TColumnInfo;
TableName: string;
ColumnName: string;
ColumnsList: TList;
begin
for ColumnInfo in FColumns do
begin
if (ColumnInfo.RealTableName <> '') and
not (ColumnInfo.RealTableName.StartsWith('[') and ColumnInfo.RealTableName.EndsWith(']')) and
(ColumnInfo.ReferencedTableColumn <> '') and
not (ColumnInfo.ReferencedTableColumn.StartsWith('[') and ColumnInfo.ReferencedTableColumn.EndsWith(']')) then
begin
TableName := LowerCase(ColumnInfo.RealTableName);
ColumnName := LowerCase(ColumnInfo.ReferencedTableColumn);
if FPrimaryKeys.TryGetValue(TableName, ColumnsList) then
begin
ColumnInfo.IsPKColumn := ColumnsList.Contains(ColumnName);
end
else
begin
// Table not found in primary keys, so column is not a primary key
ColumnInfo.IsPKColumn := False;
end;
end
else
begin
// For expressions or columns without table reference
ColumnInfo.IsPKColumn := False;
end;
function CreateValidIdentifier(const Name: string): string;
var
i: Integer;
c: Char;
begin
Result := '';
for i := 1 to Length(Name) do
begin
c := Name[i];
if c.IsLetterOrDigit or (c = '') then
Result := Result + c
else
Result := Result + ''; // Replace invalid chars with ''
end;
// Ensure the identifier does not start with a digit or invalid character
if (Result = '') or not (Result[1].IsLetter or (Result[1] = '')) then
Result := '_' + Result;
end;
function GetDelphiTypeMapping(FieldType: TFieldType; out NullableDelphiType, WriteMethod: string): Boolean;
begin
Result := True;
case FieldType of
TFieldType.ftString, TFieldType.ftWideString, TFieldType.ftMemo, TFieldType.ftWideMemo:
begin
NullableDelphiType := 'TNullable';
WriteMethod := 'Set_Info_NullableString';
end;
TFieldType.ftInteger, TFieldType.ftByte, TFieldType.ftSmallint, TFieldType.ftWord, TFieldType.ftLongWord, TFieldType.ftShortint:
begin
NullableDelphiType := 'TNullable';
WriteMethod := 'Set_Info_NullableInteger';
end;
TFieldType.ftLargeint:
begin
NullableDelphiType := 'TNullable';
WriteMethod := 'Set_Info_NullableInt64';
end;
TFieldType.ftSingle, TFieldType.ftFloat, TFieldType.ftExtended:
begin
NullableDelphiType := 'TNullable';
WriteMethod := 'Set_Info_NullableExtended';
end;
TFieldType.ftDate, TFieldType.ftTime, TFieldType.ftDateTime, TFieldType.ftTimeStamp:
begin
NullableDelphiType := 'TNullable';
WriteMethod := 'Set_Info_NullableDateTime';
end;
TFieldType.ftCurrency:
begin
NullableDelphiType := 'TNullable';
WriteMethod := 'Set_Info_NullableCurrency';
end;
TFieldType.ftFMTBcd, TFieldType.ftBCD:
begin
NullableDelphiType := 'TNullable';
WriteMethod := 'Set_Info_NullableCurrency';
end;
TFieldType.ftBoolean:
begin
NullableDelphiType := 'TNullable';
WriteMethod := 'Set_Info_NullableBoolean';
end;
else
begin
NullableDelphiType := 'TNullable';
WriteMethod := 'Set_Info_NullableVariant';
Result := False;
end;
end;
end;
Parser := TSQLParser.Create(SQLText, AConnection);
try
FieldsList := Parser.Columns; // Get the columns info
// Iterate over the columns to generate field declarations
for i := 0 to FieldsList.Count - 1 do
begin
ColumnInfo := FieldsList[i];
if not GetDelphiTypeMapping(ColumnInfo.DataType, NullableDelphiType, WriteMethod) then
begin
// Handle unsupported type if necessary
end;
// Use QueryColumnAlias as the field name or the column name
if ColumnInfo.QueryColumnAlias <> '' then
FieldName := ColumnInfo.QueryColumnAlias
else
FieldName := ColumnInfo.ReferencedTableColumn;
// Sanitize the FieldName (remove special characters, etc.)
FieldName := CreateValidIdentifier(FieldName);
FieldName := '_' + FieldName; // Prefix with '_'
// Initialize the list of attributes
AttributesList := TList<string>.Create;
try
// Build custom attributes
if not ColumnInfo.RealTableName.IsEmpty and
not ((ColumnInfo.RealTableName = '[none]') or (ColumnInfo.RealTableName = '[ambiguous]') or (ColumnInfo.RealTableName = '[unknown]')) then
begin
// Insert Table attribute
AttributesList.Add(Format('Table(''%s'')', [ColumnInfo.RealTableName]));
end;
if ColumnInfo.IsPKColumn then
begin
AttributesList.Add('PrimaryKey');
end;
if not ColumnInfo.ReferencedTableColumn.IsEmpty and (ColumnInfo.ReferencedTableColumn <> '[none]') then
begin
AttributesList.Add(Format('RefColumn(''%s'')', [ColumnInfo.ReferencedTableColumn]));
end;
// Combine attributes
if AttributesList.Count > 0 then
AttrsLine := Format(' [%s]', [String.Join(', ', AttributesList.ToArray)])
else
AttrsLine := '';
// Add field declaration
if AttrsLine <> '' then
ResultList.Add(Format('%s %s: %s;', [AttrsLine, FieldName, NullableDelphiType]))
else
ResultList.Add(Format(' %s: %s;', [FieldName, NullableDelphiType]));
finally
AttributesList.Free;
end;
end;
// Generate published property declarations
ResultList.Add(' published');
PropIndex := 0;
for i := 0 to FieldsList.Count - 1 do
begin
ColumnInfo := FieldsList[i];
if not GetDelphiTypeMapping(ColumnInfo.DataType, NullableDelphiType, WriteMethod) then
begin
// Handle unsupported type if necessary
end;
// Use the sanitized FieldName (without '_')
if ColumnInfo.QueryColumnAlias <> '' then
FieldName := ColumnInfo.QueryColumnAlias
else
FieldName := ColumnInfo.ReferencedTableColumn;
FieldName := CreateValidIdentifier(FieldName);
// PropertyName is same as FieldName
PropertyName := FieldName;
// FieldName with '_'
FieldName := '_' + FieldName;
// Add property declaration
ResultList.Add(Format(' property %s: %s index %d read %s write %s;', [PropertyName, NullableDelphiType, PropIndex, FieldName, WriteMethod]));
Inc(PropIndex);
end;
ResultList.Add(' end;');
ResultList.Add('');
finally
Parser.Free;
end;
Result := ResultList.Text;
finally
ResultList.Free;
end;
end;
Certainly! Below is a comprehensive implementation of the TQryRecArray<T> generic class in Delphi, tailored to work seamlessly with your existing ORM setup. This class is designed to execute SQL SELECT queries using TUniQuery, map the resulting fields to class properties based on the RefColumnAttribute, handle TNullable<> types appropriately, and populate a list of class instances with the query data.
Overview
TQryRecArray<T> Class: A generic class that manages a list of records of type T. It provides methods to execute SQL queries, map fields to properties using RTTI, and handle TNullable<> types with proper NULL value management.
Implementation Steps:
Define the TQryRecArray<T> Class: Includes necessary fields and methods.
Implement the Fetch Method: Utilizes RTTI to map query fields to class properties based on RefColumnAttribute.
Handle TNullable<> Types and NULL Values: Ensures that NULL database values are correctly represented in the class instances.
Provide a Usage Example: Demonstrates how to use the TQryRecArray<T> class with a sample class.
Complete Implementation
1. pixel_ORM.pas - Defining TQryRecArray<T>
Create a new unit named pixel_ORM.pas and add the following code:
unit pixel_ORM;
interface
uses
System.SysUtils, System.Classes, System.Generics.Collections, System.Rtti,
Uni, pixel_classes, ORM_CustomAttributes, Data.DB;
type
TQryRecArray<T: class, constructor> = class
private
FList: TObjectList<T>;
FConnection: TUniConnection;
FSQL: string;
procedure LoadData;
public
constructor Create(AConnection: TUniConnection; const ASQL: string);
destructor Destroy; override;
function GetList: TObjectList<T>;
property List: TObjectList<T> read GetList;
procedure Fetch; // Executes the query and loads data into FList
end;
implementation
{ TQryRecArray<T> }
constructor TQryRecArray<T>.Create(AConnection: TUniConnection; const ASQL: string);
begin
inherited Create;
FConnection := AConnection;
FSQL := ASQL;
FList := TObjectList<T>.Create(True); // Owns objects
end;
destructor TQryRecArray<T>.Destroy;
begin
FList.Free;
inherited;
end;
function TQryRecArray<T>.GetList: TObjectList<T>;
begin
Result := FList;
end;
// Helper function to set property value
procedure SetPropertyValue<T>(Obj: T; Prop: TRttiProperty; Field: TField);
var
NullableType: TRttiType;
Value: TValue;
begin
if Field.IsNull then
begin
// Setting HasValue to False
if Prop.PropertyType is TRttiInstanceType then
begin
// For TNullable<> types
Value := TValue.Empty; // TNullable implicitly handles NULL
Prop.SetValue(Obj, Value);
end;
end
else
begin
case Field.DataType of
ftString, ftWideString, ftMemo, ftWideMemo:
Prop.SetValue(Obj, Field.AsString);
ftInteger, ftSmallint, ftWord, ftLongWord, ftByte, ftShortint:
Prop.SetValue(Obj, Field.AsInteger);
ftLargeint:
Prop.SetValue(Obj, Field.AsLargeInt);
ftFloat, ftSingle, ftExtended, ftCurrency:
Prop.SetValue(Obj, Field.AsFloat);
ftBCD, ftFMTBcd:
Prop.SetValue(Obj, Field.AsCurrency);
ftBoolean:
Prop.SetValue(Obj, Field.AsBoolean);
ftDate, ftTime, ftDateTime, ftTimeStamp:
Prop.SetValue(Obj, Field.AsDateTime);
else
// For unsupported types, you can handle accordingly
Prop.SetValue(Obj, Field.Value);
end;
end;
end;
procedure TQryRecArray<T>.LoadData;
var
Query: TUniQuery;
RttiContext: TRttiContext;
RttiType: TRttiType;
Prop: TRttiProperty;
Attr: RefColumnAttribute;
Instance: T;
FieldName: string;
Field: TField;
begin
Query := TUniQuery.Create(nil);
try
Query.Connection := FConnection;
Query.SQL.Text := FSQL;
Query.Open;
RttiContext := TRttiContext.Create;
RttiType := RttiContext.GetType(T.ClassInfo);
while not Query.Eof do
begin
Instance := T.Create;
try
for Prop in RttiType.GetProperties do
begin
// Only consider published properties
if not Prop.IsPublished then
Continue;
// Find RefColumnAttribute
Attr := nil;
for var A in Prop.GetAttributes do
if A is RefColumnAttribute then
begin
Attr := RefColumnAttribute(A);
Break;
end;
if Assigned(Attr) then
begin
FieldName := Attr.ColumnName;
Field := Query.FindField(FieldName);
if Assigned(Field) then
SetPropertyValue(Instance, Prop, Field)
else
raise Exception.CreateFmt('Field "%s" not found in query.', [FieldName]);
end;
end;
FList.Add(Instance);
except
Instance.Free;
raise;
end;
Query.Next;
end;
Query.Close;
finally
Query.Free;
end;
end;
procedure TQryRecArray<T>.Fetch;
begin
FList.Clear;
LoadData;
end;
end.
Explanation
Class Declaration:
TQryRecArray<T> is a generic class where T must be a class with a parameterless constructor.
It contains a TObjectList<T> to manage instances of T, a TUniConnection for database connectivity, and a SQL string.
Constructor & Destructor:
The constructor initializes the connection, SQL query, and the object list.
The destructor ensures that all resources are properly freed.
Fetch Method:
Clears any existing data in the list.
Calls LoadData to execute the query and populate the list.
LoadData Method:
Executes the SQL query using TUniQuery.
Utilizes RTTI to iterate over the published properties of class T.
For each property with a RefColumnAttribute, it maps the corresponding field from the query to the property.
Handles TNullable<> types by checking for NULL values and setting the HasValue flag accordingly.
SetPropertyValue Procedure:
A helper procedure that assigns the value from the query field to the class property.
Correctly handles different data types and TNullable<> records.
2. Extending pixel_classes.pas with Setter Methods
To allow TQryRecArray<T> to set the properties, ensure that your TPixelUtils class includes setter methods for each TNullable<> type. Update your pixel_classes.pas as follows:
// ... (Existing code)
type
TPixelUtils = class
public
// Existing methods
// Add setter methods for TNullable<> types
class procedure Set_Info_NullableInteger(Instance: TObject; const Value: TNullable<Integer>);
class procedure Set_Info_NullableString(Instance: TObject; const Value: TNullable<String>);
class procedure Set_Info_NullableCurrency(Instance: TObject; const Value: TNullable<Currency>);
class procedure Set_Info_NullableDateTime(Instance: TObject; const Value: TNullable<TDateTime>);
// Add more setters as needed
end;
implementation
// ... (Existing code)
class procedure TPixelUtils.Set_Info_NullableInteger(Instance: TObject; const Value: TNullable<Integer>);
var
Rec: PByte;
begin
// Implement the logic to set the _EmployeeID or similar fields
// This is a placeholder. Implement according to your class structure.
end;
class procedure TPixelUtils.Set_Info_NullableString(Instance: TObject; const Value: TNullable<String>);
begin
// Similar implementation for string properties
end;
class procedure TPixelUtils.Set_Info_NullableCurrency(Instance: TObject; const Value: TNullable<Currency>);
begin
// Similar implementation for currency properties
end;
class procedure TPixelUtils.Set_Info_NullableDateTime(Instance: TObject; const Value: TNullable<TDateTime>);
begin
// Similar implementation for TDateTime properties
end;
// ... (Implement other setters as needed)
end.
Note: Implement the setter methods (Set_Info_NullableInteger, Set_Info_NullableString, etc.) according to your class structure. These methods are placeholders and need to be properly implemented to assign values to the corresponding fields in your classes.
3. Example Usage
Assuming you have a TEmployeeProject class as defined in your formgerenc_Classes.pas unit, here's how you can use the TQryRecArray<T> class to fetch data and populate a list of TEmployeeProject instances.
uses
System.SysUtils, Uni, pixel_ORM, formgerenc_Classes;
procedure ExampleUsage;
var
Connection: TUniConnection;
QryRecArray: TQryRecArray<TEmployeeProject>;
EmployeeProject: TEmployeeProject;
begin
// Initialize the database connection
Connection := TUniConnection.Create(nil);
try
Connection.Provider := 'PG'; // Example for PostgreSQL
Connection.Database := 'your_database';
Connection.Username := 'your_username';
Connection.Password := 'your_password';
Connection.Server := 'localhost';
Connection.Port := 5432;
Connection.Connect;
// Define your SQL SELECT query
var SQLText := 'SELECT e.emp_id, e.dept_id, e.emp_name, p.proj_id, p.proj_name, ' +
'p.proj_budget, p.proj_date, p.proj_starttime ' +
'FROM employees e ' +
'JOIN projects p ON e.proj_id = p.proj_id ' +
'WHERE e.dept_id = :DeptID';
// Create an instance of TQryRecArray with TEmployeeProject
QryRecArray := TQryRecArray<TEmployeeProject>.Create(Connection, SQLText);
try
// Optionally, set any parameters before fetching
// For example, if your SQL has :DeptID parameter
// QryRecArray.Query.ParamByName('DeptID').AsInteger := 10;
// Fetch data
QryRecArray.Fetch;
// Iterate over the results
for EmployeeProject in QryRecArray.List do
begin
// Access properties
if EmployeeProject.EmployeeID.HasValue then
WriteLn('Employee ID: ', EmployeeProject.EmployeeID.Value)
else
WriteLn('Employee ID: NULL');
if EmployeeProject.EmployeeName.HasValue then
WriteLn('Employee Name: ', EmployeeProject.EmployeeName.Value)
else
WriteLn('Employee Name: NULL');
// Similarly, access other properties
// ...
WriteLn('---');
end;
finally
QryRecArray.Free;
end;
finally
Connection.Free;
end;
end;
Explanation
Database Connection:
Initializes and configures the TUniConnection with the appropriate database parameters.
Connects to the database.
SQL Query:
Defines a SELECT statement joining employees and projects tables, with a parameter :DeptID.
Creating TQryRecArray Instance:
Instantiates TQryRecArray<TEmployeeProject> with the database connection and SQL query.
Note: If your SQL query includes parameters (like :DeptID), you'll need to modify the TQryRecArray<T> class to accept and set parameters before executing the query.
Fetching Data:
Calls the Fetch method to execute the query and populate the List with TEmployeeProject instances.
Iterating Over Results:
Iterates through each TEmployeeProject in the List.
Accesses properties, checking if they have values (HasValue) before using them.
Cleanup:
Frees the QryRecArray and Connection instances to release resources.
4. Handling SQL Parameters
If your SQL queries include parameters (e.g., :DeptID), you'll need to enhance the TQryRecArray<T> class to accept and set these parameters before executing the query. Here's how you can modify the class to support this:
a. Update TQryRecArray<T> Class
Add a method to set parameters:
type
TQryRecArray<T: class, constructor> = class
// Existing declarations
private
// Existing fields
procedure LoadData;
// New method
procedure SetParameters(Query: TUniQuery);
public
// Existing methods
procedure Fetch; // Executes the query and loads data into FList
// New method
procedure AddParameter(const Name: string; const Value: TValue);
end;
Implement parameter handling:
// New private field to store parameters
private
FParameters: TDictionary<string, TValue>;
constructor TQryRecArray<T>.Create(AConnection: TUniConnection; const ASQL: string);
begin
inherited Create;
FConnection := AConnection;
FSQL := ASQL;
FList := TObjectList<T>.Create(True); // Owns objects
FParameters := TDictionary<string, TValue>.Create;
end;
destructor TQryRecArray<T>.Destroy;
begin
FParameters.Free;
FList.Free;
inherited;
end;
// AddParameter method
procedure TQryRecArray<T>.AddParameter(const Name: string; const Value: TValue);
begin
if FParameters.ContainsKey(Name) then
FParameters[Name] := Value
else
FParameters.Add(Name, Value);
end;
// SetParameters method
procedure TQryRecArray<T>.SetParameters(Query: TUniQuery);
var
Param: TParam;
Key: string;
Value: TValue;
begin
for Key in FParameters.Keys do
begin
Value := FParameters[Key];
Param := Query.ParamByName(Key);
if Param <> nil then
begin
case Value.Kind of
tkInteger: Param.AsInteger := Value.AsInteger;
tkInt64: Param.AsLargeInt := Value.AsInt64;
tkFloat: Param.AsFloat := Value.AsExtended;
tkString, tkLString, tkWString, tkUString: Param.AsString := Value.AsString;
tkBoolean: Param.AsBoolean := Value.AsBoolean;
// Add more type cases as needed
else
Param.Value := Value;
end;
end
else
raise Exception.CreateFmt('Parameter "%s" not found in SQL query.', [Key]);
end;
end;
// Modify LoadData to set parameters
procedure TQryRecArray<T>.LoadData;
begin
// Existing implementation
// Before executing the query, set parameters
Query := TUniQuery.Create(nil);
try
Query.Connection := FConnection;
Query.SQL.Text := FSQL;
// Set parameters
SetParameters(Query);
Query.Open;
// Rest of the code...
finally
Query.Free;
end;
end;
b. Adjust Example Usage
Modify the example usage to set parameters:
// ... (Inside ExampleUsage procedure)
// Create an instance of TQryRecArray with TEmployeeProject
QryRecArray := TQryRecArray<TEmployeeProject>.Create(Connection, SQLText);
try
// Set parameter :DeptID to 10
QryRecArray.AddParameter('DeptID', 10);
// Fetch data
QryRecArray.Fetch;
// Iterate over the results
for EmployeeProject in QryRecArray.List do
begin
// Access properties as before
// ...
end;
finally
QryRecArray.Free;
end;
// ...
5. Enhancing SetPropertyValue for TNullable<> Types
To correctly handle TNullable<> types, enhance the SetPropertyValue procedure to utilize the TPixelUtils class for setting property values. Here's an improved version:
procedure SetPropertyValue<T>(Obj: T; Prop: TRttiProperty; Field: TField);
var
NullableType: TRttiType;
Value: TValue;
Method: TRttiMethod;
begin
// Check if the property type is a generic TNullable<>
if (Prop.PropertyType.TypeKind = tkRecord) and
(Prop.PropertyType.Name.StartsWith('TNullable')) then
begin
// Use RTTI to set the Value and HasValue
if Field.IsNull then
begin
// Assignable as implicit via TNullable.JSONObject
Value := TValue.From<TNullable<Object>>(NullValue);
end
else
begin
// Assign the actual value
case Field.DataType of
ftString, ftWideString, ftMemo, ftWideMemo:
Value := TValue.From<string>(Field.AsString);
ftInteger, ftSmallint, ftWord, ftLongWord, ftByte, ftShortint:
Value := TValue.From<Integer>(Field.AsInteger);
ftLargeint:
Value := TValue.From<Int64>(Field.AsLargeInt);
ftFloat, ftSingle, ftExtended, ftCurrency:
Value := TValue.From<Extended>(Field.AsFloat);
ftBCD, ftFMTBcd:
Value := TValue.From<Currency>(Field.AsCurrency);
ftBoolean:
Value := TValue.From<Boolean>(Field.AsBoolean);
ftDate, ftTime, ftDateTime, ftTimeStamp:
Value := TValue.From<TDateTime>(Field.AsDateTime);
else
Value := Field.Value;
end;
end;
// Assign to the property
Prop.SetValue(Obj, Value);
end
else
begin
// Handle non-TNullable<> types if necessary
// For simplicity, only handling TNullable<> in this example
end;
end;
Note: This implementation assumes that TNullable<> types have implicit operators to handle assignments. Depending on your specific implementation of TNullable<>, you may need to adjust this procedure accordingly.
Conclusion
The TQryRecArray<T> generic class provides a robust solution for executing SQL SELECT queries, mapping results to class properties using RTTI and custom attributes, handling nullable types, and managing a list of populated class instances. By following the implementation steps and integrating the provided code, you can streamline data access and ORM functionalities within your Delphi applications.
Additional Considerations
Error Handling: Ensure that appropriate error handling is in place, especially when dealing with database connections and data mapping.
Performance: For large datasets, consider implementing lazy loading or pagination to optimize performance.
Extensibility: Enhance the class to support more complex scenarios, such as relationships, transactions, and more advanced querying capabilities.
Testing: Rigorously test the implementation with various SQL queries and data types to ensure reliability and correctness.
Feel free to tailor the provided code to better fit your application's specific needs and architectural design.