Given the Delphi units below, that receives a SQL SELECT query and create a class:
showmessage(GenerateDelphiClassFromQuery('SELECT caixa_id,caixa_nome as nomedocaixa,(CURRENT_TIMESTAMP) as cx_date FROM caixa','CaixaORM',DM.LocalServer));
Given the class generated by GenerateDelphiClassFromQuery, I need Delphi code (using Rtti and other resources available on the latest Delphi verions) that gets a TUniQuery that matches that generated the corresponding class and populate it
///
/// 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;
code
/// <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
code
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;
code
/// <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;
code
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]);
code
// 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;
code
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);
code
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;
type
TInstanceCreator<T: class, constructor> = class
public
class function CreateInstances(AConnection: TUniConnection): TList;
end;
{ TInstanceCreator }
class function TInstanceCreator.CreateInstances(AConnection: TUniConnection): TList;
var
Context: TRttiContext;
RttiType: TRttiType;
RttiProperty: TRttiProperty;
Attr: TCustomAttribute;
ColumnList: TList;
TableList: TList;
SQLSelect: TStringList;
Query: TUniQuery;
Instance: T;
FieldName: string;
PropertyMap: TDictionary<string, TRttiProperty>;
ColumnAlias: string;
Value: TValue;
TableName: string;
ColumnName: string;
ColumnExpr: string;
PropType: TRttiType;
ValueType: PTypeInfo;
NullableValue: TValue;
begin
Result := TList.Create;
Context := TRttiContext.Create;
try
RttiType := Context.GetType(TypeInfo(T));
ColumnList := TList.Create;
TableList := TList.Create;
PropertyMap := TDictionary<string, TRttiProperty>.Create;
try
// Collect information about tables and columns
for RttiProperty in RttiType.GetProperties do
begin
TableName := '';
ColumnName := '';
ColumnAlias := RttiProperty.Name;
ColumnExpr := '';
for Attr in RttiProperty.GetAttributes do
begin
if Attr is TableAttribute then
begin
TableName := TableAttribute(Attr).TableName;
if not TableList.Contains(TableName) then
TableList.Add(TableName);
end
else if Attr is RefColumnAttribute then
begin
ColumnName := RefColumnAttribute(Attr).ColumnName;
end;
end;
if (TableName <> '') and (ColumnName <> '') then
begin
ColumnExpr := Format('%s.%s AS %s', [TableName, ColumnName, ColumnAlias]);
end
else
begin
// Handle expressions or columns without specific table/column attributes
ColumnExpr := ColumnAlias; // Assume the field name matches property name
end;
ColumnList.Add(ColumnExpr);
// Map the column alias to the property for later assignment
PropertyMap.Add(ColumnAlias.ToLower, RttiProperty);
end;
code
// Build the SQL
SQLSelect := TStringList.Create;
try
SQLSelect.Add('SELECT');
SQLSelect.Add(String.Join(', ', ColumnList.ToArray));
SQLSelect.Add('FROM');
SQLSelect.Add(String.Join(', ', TableList.ToArray));
// Execute the query
Query := TUniQuery.Create(nil);
try
Query.Connection := AConnection;
Query.SQL.Text := SQLSelect.Text;
Query.Open;
while not Query.Eof do
begin
Instance := T.Create;
for FieldName in PropertyMap.Keys do
begin
if Query.FindField(FieldName) <> nil then
begin
RttiProperty := PropertyMap[FieldName.ToLower];
PropType := RttiProperty.PropertyType;
// Check if the property is of type TNullable<T>
if (PropType.IsGenericType) and (PropType.QualifiedName.StartsWith('TNullable<')) then
begin
// Get the underlying type of T in TNullable<T>
ValueType := PropType.GetGenericArguments[0].Handle;
if Query.FieldByName(FieldName).IsNull then
begin
// Create an empty TNullable<T>
NullableValue := TValue.From(PropType.MetaclassType.Create);
end
else
begin
case ValueType.Kind of
tkInteger:
NullableValue := TValue.From(
TValue.Make(@Query.FieldByName(FieldName).AsInteger, ValueType)
);
tkInt64:
NullableValue := TValue.From(
TValue.Make(@Query.FieldByName(FieldName).AsLargeInt, ValueType)
);
tkFloat:
if ValueType = TypeInfo(TDateTime) then
begin
var DateTimeValue: TDateTime := Query.FieldByName(FieldName).AsDateTime;
NullableValue := TValue.From(
TValue.Make(@DateTimeValue, ValueType)
);
end
else
begin
var FloatValue: Double := Query.FieldByName(FieldName).AsFloat;
NullableValue := TValue.From(
TValue.Make(@FloatValue, ValueType)
);
end;
tkUString, tkString, tkLString, tkWString:
NullableValue := TValue.From(
Query.FieldByName(FieldName).AsString
);
tkVariant:
NullableValue := TValue.From(
Query.FieldByName(FieldName).Value
);
tkBool:
NullableValue := TValue.From(
Query.FieldByName(FieldName).AsBoolean
);
else
// Handle other types as needed
NullableValue := TValue.Empty;
end;
// Wrap the value in TNullable<T>
NullableValue := TValue.From(PropType.MetaclassType.Create(NullableValue.AsObject));
end;
// Set the property value
RttiProperty.SetValue(TObject(Instance), NullableValue);
end
else
begin
// For non-nullable properties
if Query.FieldByName(FieldName).IsNull then
Value := TValue.Empty
else
Value := TValue.FromVariant(Query.FieldByName(FieldName).Value);
RttiProperty.SetValue(TObject(Instance), Value);
end;
end;
end;
Result.Add(Instance);
Query.Next;
end;
finally
Query.Free;
end;
finally
SQLSelect.Free;
end;
finally
ColumnList.Free;
TableList.Free;
PropertyMap.Free;
end;
finally
Context.Free;
end;
end;
end.
To address the issues in your ORM_DataMapper unit, we'll focus on the following key areas:
Correct Usage of TRttiContext:
TRttiContext is a record, not a class. It manages its own memory and doesn't require explicit creation or destruction.
Handling TNullable<T> Properties:
Properly instantiate and assign values to TNullable<T> properties using RTTI.
Ensure that nullable types are handled generically to accommodate different underlying types.
Consistent Case Handling for Property Mapping:
Use a case-insensitive dictionary for mapping to avoid issues with varying cases in field names.
Support table aliases and ensure the generated SQL is valid.
Enhanced Type Mapping:
Improve the mapping between database field types and Delphi types, ensuring all necessary types are covered.
Below is the revised ORM_DataMapper unit addressing these issues:
delphi
unit ORM_DataMapper;
interface
uses
System.Rtti, System.TypInfo, System.Generics.Collections, Data.DB, Uni, System.SysUtils,
System.Variants, Classes, ORM_CustomAttributes;
type
TInstanceCreator<T: class, constructor> = class
public
class function CreateInstances(AConnection: TUniConnection): TList<T>;
end;
implementation
uses
System.Generics.Defaults;
{ TInstanceCreator<T> }
class function TInstanceCreator<T>.CreateInstances(AConnection: TUniConnection): TList<T>;
var
Context: TRttiContext;
RttiType: TRttiType;
RttiProperty: TRttiProperty;
Attr: TCustomAttribute;
ColumnList: TList<string>;
TableList: TList<string>;
SQLSelect: TStringList;
Query: TUniQuery;
Instance: T;
FieldName: string;
PropertyMap: TDictionary<string, TRttiProperty>;
ColumnAlias: string;
Value: TValue;
TableName: string;
ColumnName: string;
ColumnExpr: string;
PropType: TRttiType;
NullableType: TRttiType;
NullableInstance: TValue;
GenArgType: TRttiType;
begin
Result := TList<T>.Create;
Context := TRttiContext.Create;
try
RttiType := Context.GetType(T);
if not Assigned(RttiType) then
raise Exception.CreateFmt('Type information for %s not found.', [T.ClassName]);
ColumnList := TList<string>.Create;
TableList := TList<string>.Create;
PropertyMap := TDictionary<string, TRttiProperty>.Create([doOwnsValues, doCaseInsensitiveKeys]);
try
// Collect information about tables and columns
for RttiProperty in RttiType.GetProperties do
begin
TableName := '';
ColumnName := '';
ColumnAlias := RttiProperty.Name;
ColumnExpr := '';
for Attr in RttiProperty.GetAttributes do
begin
if Attr is TableAttribute then
begin
TableName := TableAttribute(Attr).TableName;
if not TableList.Contains(TableName) then
TableList.Add(TableName);
end
else if Attr is RefColumnAttribute then
begin
ColumnName := RefColumnAttribute(Attr).ColumnName;
end;
end;
if (TableName <> '') and (ColumnName <> '') then
begin
ColumnExpr := Format('%s.%s AS %s', [TableName, ColumnName, ColumnAlias]);
end
else
begin
// Handle expressions or columns without specific table/column attributes
ColumnExpr := ColumnAlias; // Assume the field name matches property name
end;
ColumnList.Add(ColumnExpr);
// Map the column alias to the property for later assignment
PropertyMap.Add(ColumnAlias, RttiProperty);
end;
// Build the SQL
SQLSelect := TStringList.Create;
try
SQLSelect.Add('SELECT');
SQLSelect.Add(String.Join(', ', ColumnList.ToArray));
SQLSelect.Add('FROM');
SQLSelect.Add(String.Join(', ', TableList.ToArray));
// Execute the query
Query := TUniQuery.Create(nil);
try
Query.Connection := AConnection;
Query.SQL.Text := SQLSelect.Text;
Query.Open;
while not Query.Eof do
begin
Instance := T.Create;
for FieldName in PropertyMap.Keys do
begin
if Query.FindField(FieldName) <> nil then
begin
RttiProperty := PropertyMap[FieldName];
PropType := RttiProperty.PropertyType;
// Check if the property is of type TNullable<T>
if (PropType.IsInstance) and
(PropType.AsInstance.MetaclassType.InheritsFrom(TNullable<Variant>.ClassType)) then
begin
// Handling TNullable<T>
if Query.FieldByName(FieldName).IsNull then
begin
// Assign an empty TNullable<T>
NullableInstance := TValue.From<TNullable<Variant>>(TNullable<Variant>.Create);
end
else
begin
// Determine the generic type argument
if PropType.GetGenericArguments.Count <> 1 then
raise Exception.Create('TNullable must have exactly one generic type argument.');
GenArgType := PropType.GetGenericArguments[0];
// Create a TNullable<T> instance and set its value
if GenArgType.TypeKind = tkInteger then
begin
NullableInstance := TValue.From<TNullable<Integer>>(TNullable<Integer>.Create(Query.FieldByName(FieldName).AsInteger));
end
else if GenArgType.TypeKind = tkInt64 then
begin
NullableInstance := TValue.From<TNullable<Int64>>(TNullable<Int64>.Create(Query.FieldByName(FieldName).AsLargeInt));
end
else if GenArgType.TypeKind = tkFloat then
begin
if GenArgType.Handle = TypeInfo(TDateTime) then
NullableInstance := TValue.From<TNullable<TDateTime>>(TNullable<TDateTime>.Create(Query.FieldByName(FieldName).AsDateTime))
else
NullableInstance := TValue.From<TNullable<Double>>(TNullable<Double>.Create(Query.FieldByName(FieldName).AsFloat));
end
else if GenArgType.TypeKind in [tkUString, tkLString, tkWString, tkString] then
begin
NullableInstance := TValue.From<TNullable<String>>(TNullable<String>.Create(Query.FieldByName(FieldName).AsString));
end
else if GenArgType.TypeKind = tkBool then
begin
NullableInstance := TValue.From<TNullable<Boolean>>(TNullable<Boolean>.Create(Query.FieldByName(FieldName).AsBoolean));
end
else if GenArgType.TypeKind = tkCurrency then
begin
NullableInstance := TValue.From<TNullable<Currency>>(TNullable<Currency>.Create(Query.FieldByName(FieldName).AsCurrency));
end
else
begin
// Extend as needed for other types
NullableInstance := TValue.From<TNullable<Variant>>(TNullable<Variant>.Create(Query.FieldByName(FieldName).Value));
end;
end;
// Set the property value
RttiProperty.SetValue(Instance, NullableInstance);
end
else
begin
// For non-nullable properties
if Query.FieldByName(FieldName).IsNull then
Value := TValue.Empty
else
begin
// Map based on the property type
case PropType.TypeKind of
tkInteger:
Value := TValue.From<Integer>(Query.FieldByName(FieldName).AsInteger);
tkInt64:
Value := TValue.From<Int64>(Query.FieldByName(FieldName).AsLargeInt);
tkFloat:
if PropType.Handle = TypeInfo(TDateTime) then
Value := TValue.From<TDateTime>(Query.FieldByName(FieldName).AsDateTime)
else
Value := TValue.From<Double>(Query.FieldByName(FieldName).AsFloat);
tkUString, tkLString, tkWString, tkString:
Value := TValue.From<String>(Query.FieldByName(FieldName).AsString);
tkBoolean:
Value := TValue.From<Boolean>(Query.FieldByName(FieldName).AsBoolean);
tkCurrency:
Value := TValue.From<Currency>(Query.FieldByName(FieldName).AsCurrency);
else
// Handle other types or use Variant as a fallback
Value := TValue.FromVariant(Query.FieldByName(FieldName).Value);
end;
end;
// Set the property value
RttiProperty.SetValue(Instance, Value);
end;
end;
end;
Result.Add(Instance);
Query.Next;
end;
finally
Query.Free;
end;
finally
SQLSelect.Free;
end;
finally
ColumnList.Free;
TableList.Free;
PropertyMap.Free;
end;
finally
// TRttiContext does not need to be explicitly freed
// Removed Context.Free
end;
end;
end.
Detailed Explanation of Corrections:
TRttiContext Handling:
Issue: The original code incorrectly called TRttiContext.Create and attempted to free it, which is not necessary since TRttiContext is a record.
Correction: Removed the explicit creation and destruction of TRttiContext. Instead, declare it as a variable, and it will manage its own lifetime.
delphi
var
Context: TRttiContext;
begin
Context := TRttiContext.Create;
// No need to call Context.Free
end;
Handling TNullable<T> Properties:
Issue: The original code attempted to instantiate TNullable<T> using MetaclassType.Create, which isn't appropriate for generic types.
Correction: Implemented a type-specific instantiation for TNullable<T> by checking the underlying generic type argument and creating instances accordingly.
delphi
if GenArgType.TypeKind = tkInteger then
begin
NullableInstance := TValue.From<TNullable<Integer>>(TNullable<Integer>.Create(Query.FieldByName(FieldName).AsInteger));
end
else if GenArgType.TypeKind = tkInt64 then
begin
NullableInstance := TValue.From<TNullable<Int64>>(TNullable<Int64>.Create(Query.FieldByName(FieldName).AsLargeInt));
end
...
Assumption:TNullable<T> has a constructor that accepts a value of type T. Adjust the instantiation logic based on your actual TNullable<T> implementation.
Consistent Case Handling for PropertyMap:
Issue: The original code used ToLower for keys but didn't consistently handle case insensitivity.
Correction: Initialized PropertyMap with [doCaseInsensitiveKeys] to make the dictionary case-insensitive, removing the need to manually convert keys to lowercase.
Notes and Assumptions:
TNullable<T> Implementation:
The corrected code assumes that TNullable<T> has a constructor that accepts a value of type T. If your TNullable<T> implementation differs, adjust the instantiation logic accordingly.
Handling Additional Types:
Extend the type mapping as needed to handle additional types used in your database schema.
SQL Generation for Multiple Tables:
If your use case involves specific join conditions or complex queries, consider enhancing the SQL generation logic to accommodate those requirements.
Property Setters:
Ensure that the properties in your generated classes correctly reflect the Set_Info_Nullable<Type> methods, handling the assignment logic appropriately.
Example Usage:
Given your example:
delphi
showmessage(GenerateDelphiClassFromQuery('SELECT caixa_id, caixa_nome as nomedocaixa, (CURRENT_TIMESTAMP) as cx_date FROM caixa','CaixaORM', DM.LocalServer));
You can use the TInstanceCreator as follows:
delphi
var
CaixaList: TList<TCaixaORM>;
begin
CaixaList := TInstanceCreator<TCaixaORM>.CreateInstances(DM.LocalServer);
try
// Use CaixaList as needed
finally
CaixaList.Free;
end;
end;
Ensure that your generated TCaixaORM class aligns with the expectations of the TInstanceCreator, including appropriate constructors and property setters.
By implementing these corrections and enhancements, your ORM_DataMapper should function correctly, efficiently mapping database query results to your generated ORM classes using RTTI and handling nullable types appropriately.
Issue: The original SQL generation can lead to Cartesian products when multiple tables are involved without proper joins.
Correction: Ensure that the generated SQL includes proper joins or handles multiple tables as intended. For simplicity, this correction assumes that multiple tables are intentionally included. If your use case requires specific join types, you'll need to extend the SQL generation logic accordingly.
Enhanced Type Mapping:
Issue: The original type mapping was incomplete and didn't handle all possible field types.
Correction: Expanded the type mapping within the non-nullable property assignment to cover more types and provide a fallback using Variant.
delphi
case PropType.TypeKind of
tkInteger:
Value := TValue.From<Integer>(Query.FieldByName(FieldName).AsInteger);
tkInt64:
Value := TValue.From<Int64>(Query.FieldByName(FieldName).AsLargeInt);
tkFloat:
if PropType.Handle = TypeInfo(TDateTime) then
Value := TValue.From<TDateTime>(Query.FieldByName(FieldName).AsDateTime)
else
Value := TValue.From<Double>(Query.FieldByName(FieldName).AsFloat);
tkUString, tkLString, tkWString, tkString:
Value := TValue.From<String>(Query.FieldByName(FieldName).AsString);
tkBoolean:
Value := TValue.From<Boolean>(Query.FieldByName(FieldName).AsBoolean);
tkCurrency:
Value := TValue.From<Currency>(Query.FieldByName(FieldName).AsCurrency);
else
// Handle other types or use Variant as a fallback
Value := TValue.FromVariant(Query.FieldByName(FieldName).Value);
end;
Error Handling and Validation:
Issue: The original code didn't include sufficient error handling.
Correction: Added validation to ensure that TNullable<T> has exactly one generic type argument, and raised meaningful exceptions where appropriate.
Memory Management:
Ensured that all dynamically created objects like TList<string>, TStringList, and TDictionary are properly freed using try...finally blocks to prevent memory leaks.