Certainly! Below is the revised GenerateDelphiClassFromQuery function. It has been adjusted to:
- Use the
TSQLParser from the SQLParserEnhanced unit to parse the SELECT query.
- Include data type information in
TColumnInfo.
- Map SQL data types to Delphi data types accurately.
- Use good programming practices, including proper resource management and error handling.
- Sanitize field and property names to ensure they are valid Delphi identifiers.
- Handle primary keys correctly based on the parser's information.
Adjustments in the SQLParserEnhanced Unit:
First, we need to adjust the SQLParserEnhanced unit to include data type information in TColumnInfo and provide methods to assign data types to columns.
Add DataType to TColumnInfo:
TColumnInfo = class
private
FFullName: string;
FRealSchemaName: string;
FRealTableName: string;
FReferencedTableColumn: string;
FQueryColumnAlias: string;
FIsPKColumn: Boolean;
FDataType: string;
public
property FullName: string read FFullName write FFullName;
property RealSchemaName: string read FRealSchemaName write FRealSchemaName;
property RealTableName: string read FRealTableName write FRealTableName;
property ReferencedTableColumn: string read FReferencedTableColumn write FReferencedTableColumn;
property QueryColumnAlias: string read FQueryColumnAlias write FQueryColumnAlias;
property IsPKColumn: Boolean read FIsPKColumn write FIsPKColumn;
property DataType: string read FDataType write FDataType;
end;
Add AssignDataTypesToColumns Method in TSQLParser:
procedure TSQLParser.AssignDataTypesToColumns;
var
ColumnInfo: TColumnInfo;
Query: TUniQuery;
SchemaName, TableName, ColumnName, DataType: string;
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
SchemaName := ColumnInfo.RealSchemaName;
TableName := ColumnInfo.RealTableName;
ColumnName := ColumnInfo.ReferencedTableColumn;
// Query the information_schema.COLUMNS to get DATA_TYPE
Query := TUniQuery.Create(nil);
try
Query.Connection := FConnection;
Query.SQL.Text := 'SELECT DATA_TYPE, COLUMN_TYPE FROM information_schema.COLUMNS ' +
'WHERE TABLE_SCHEMA = :SchemaName AND TABLE_NAME = :TableName AND COLUMN_NAME = :ColumnName';
Query.ParamByName('SchemaName').AsString := SchemaName;
Query.ParamByName('TableName').AsString := TableName;
Query.ParamByName('ColumnName').AsString := ColumnName;
Query.Open;
if not Query.Eof then
begin
// Use COLUMN_TYPE to get full type info (e.g., 'int(11)')
DataType := Query.FieldByName('COLUMN_TYPE').AsString;
ColumnInfo.DataType := DataType;
end
else
begin
ColumnInfo.DataType := 'unknown';
end;
Query.Close;
finally
Query.Free;
end;
end
else
begin
ColumnInfo.DataType := 'unknown';
end;
end;
end;
Revised GenerateDelphiClassFromQuery Function:
function GenerateDelphiClassFromSQL(const SQLText: string; const ClassName: string; Connection: TUniConnection): string;
var
Parser: TSQLParser;
ColumnInfo: TColumnInfo;
FieldDeclarations, PropertyDeclarations: TStringList;
DelphiFieldType, FieldName, PropertyName: string;
ResultBuilder: TStringBuilder;
IsPrimaryKey: Boolean;
function SanitizeDelphiIdentifier(const Identifier: string): string;
const
DelphiReservedWords: array[0..136] of string = (
'and', 'array', 'as', 'asm', 'begin', 'case', 'class', 'const', 'constructor',
'destructor', 'dispinterface', 'div', 'do', 'downto', 'else', 'end', 'except',
'exports', 'file', 'finalization', 'finally', 'for', 'function', 'goto', 'if',
'implementation', 'in', 'inherited', 'initialization', 'inline', 'interface',
'is', 'label', 'library', 'mod', 'nil', 'not', 'object', 'of', 'or',
'out', 'packed', 'procedure', 'program', 'property', 'raise', 'record',
'repeat', 'resourcestring', 'set', 'shl', 'shr', 'string', 'then', 'threadvar',
'to', 'try', 'type', 'unit', 'until', 'uses', 'var', 'while', 'with', 'xor',
'private', 'protected', 'public', 'published', 'automated', 'abstract',
'override', 'virtual', 'dynamic', 'static', 'sealed', 'partial', 'strict',
'unsafe', 'sealed', 'platform', 'deprecated', 'experimental', 'absolute',
'assembler', 'cdecl', 'export', 'external', 'far', 'forward', 'interrupt',
'near', 'pascal', 'register', 'safecall', 'stdcall', 'varargs', 'write',
'read', 'default', 'nodefault', 'stored', 'implements', 'readonly', 'writeonly',
'contains', 'index', 'reintroduce', 'overload', 'message', 'dispID',
'dynamic', 'abstract', 'sealed', 'weak', 'reference', 'type', 'unit',
'library', 'and', 'or', 'not', 'div', 'mod', 'shl', 'shr', 'as', 'is', 'in'
);
var
ReservedWord: string;
CleanedIdentifier: string;
begin
// Remove invalid characters
CleanedIdentifier := '';
for var c in Identifier do
begin
if c.IsLetterOrDigit or (c = '_') then
CleanedIdentifier := CleanedIdentifier + c
else
CleanedIdentifier := CleanedIdentifier + '_';
end;
// Ensure the identifier doesn't start with a digit
if (Length(CleanedIdentifier) > 0) and CharInSet(CleanedIdentifier[1], ['0'..'9']) then
CleanedIdentifier := '_' + CleanedIdentifier;
// Ensure the identifier is not a reserved word
for ReservedWord in DelphiReservedWords do
begin
if SameText(CleanedIdentifier, ReservedWord) then
begin
CleanedIdentifier := '_' + CleanedIdentifier;
Break;
end;
end;
Result := CleanedIdentifier;
end;
function MapSQLDataTypeToDelphi(const SQLDataType: string): string;
var
BaseType: string;
ParenPos: Integer;
begin
// Simplify the SQLDataType to its base type (e.g., 'int' from 'int(11)')
BaseType := LowerCase(SQLDataType);
BaseType := Trim(BaseType);
// Remove any parenthesis and content inside
ParenPos := Pos('(', BaseType);
if ParenPos > 0 then
BaseType := Copy(BaseType, 1, ParenPos -1);
// Handling 'unsigned' keyword
BaseType := StringReplace(BaseType, 'unsigned', '', [rfReplaceAll]);
BaseType := Trim(BaseType);
if (BaseType = 'varchar') or (BaseType = 'char') or (BaseType = 'text') or (BaseType = 'longtext') or (BaseType = 'mediumtext') or (BaseType = 'tinytext') then
Result := 'string'
else if (BaseType = 'int') or (BaseType = 'integer') or (BaseType = 'smallint') or (BaseType = 'tinyint') or (BaseType = 'mediumint') then
Result := 'Integer'
else if (BaseType = 'bigint') then
Result := 'Int64'
else if (BaseType = 'float') or (BaseType = 'double') or (BaseType = 'real') then
Result := 'Double'
else if (BaseType = 'decimal') or (BaseType = 'numeric') then
Result := 'Currency'
else if (BaseType = 'date') or (BaseType = 'datetime') or (BaseType = 'timestamp') then
Result := 'TDateTime'
else if (BaseType = 'time') then
Result := 'TTime'
else if (BaseType = 'year') then
Result := 'Word'
else if (BaseType = 'bit') then
Result := 'Boolean'
else if (BaseType = 'blob') or (BaseType = 'binary') or (BaseType = 'varbinary') or (BaseType = 'mediumblob') or (BaseType = 'longblob') or (BaseType = 'tinyblob') then
Result := 'TBytes'
else
Result := 'Variant'; // Default to Variant for unsupported types
end;
begin
Parser := TSQLParser.Create(SQLText, Connection);
try
// Assign data types to columns
Parser.AssignDataTypesToColumns;
FieldDeclarations := TStringList.Create;
PropertyDeclarations := TStringList.Create;
try
for ColumnInfo in Parser.Columns do
begin
// Map SQL data type to Delphi data type
DelphiFieldType := MapSQLDataTypeToDelphi(ColumnInfo.DataType);
// Determine FieldName and PropertyName
if not ColumnInfo.QueryColumnAlias.IsEmpty then
PropertyName := ColumnInfo.QueryColumnAlias
else if not ColumnInfo.ReferencedTableColumn.IsEmpty and (ColumnInfo.ReferencedTableColumn <> '[none]') then
PropertyName := ColumnInfo.ReferencedTableColumn
else
PropertyName := 'UnknownColumn';
// Sanitize PropertyName and FieldName
PropertyName := SanitizeDelphiIdentifier(PropertyName);
FieldName := 'F' + PropertyName;
// Check if it's a primary key
IsPrimaryKey := ColumnInfo.IsPKColumn;
// Generate field declaration with optional attributes
if IsPrimaryKey then
FieldDeclarations.Add(Format(' [PrimaryKey] %s: %s;', [FieldName, DelphiFieldType]))
else
FieldDeclarations.Add(Format(' %s: %s;', [FieldName, DelphiFieldType]));
// Generate property declaration
PropertyDeclarations.Add(Format(' property %s: %s read %s write %s;', [PropertyName, DelphiFieldType, FieldName, FieldName]));
end;
ResultBuilder := TStringBuilder.Create;
try
ResultBuilder.AppendLine('type');
ResultBuilder.AppendLine(Format(' T%s = class', [ClassName]));
ResultBuilder.AppendLine(' private');
ResultBuilder.AppendLine(FieldDeclarations.Text.TrimRight);
ResultBuilder.AppendLine(' public');
ResultBuilder.AppendLine(PropertyDeclarations.Text.TrimRight);
ResultBuilder.AppendLine(' end;');
Result := ResultBuilder.ToString;
finally
ResultBuilder.Free;
end;
finally
FieldDeclarations.Free;
PropertyDeclarations.Free;
end;
finally
Parser.Free;
end;
end;
Explanation:
-
Data Type Mapping:
- The function now uses the
MapSQLDataTypeToDelphi function to map SQL data types to Delphi data types accurately.
- This function removes any size specifications (e.g.,
(11)) and handles unsigned types.
- It provides a default to
Variant for unsupported types.
-
Sanitizing Identifiers:
- The
SanitizeDelphiIdentifier function ensures that field and property names are valid Delphi identifiers.
- It replaces invalid characters with underscores, prefixes identifiers that start with digits, and avoids Delphi reserved words.
-
Using TSQLParser:
- The function leverages the
TSQLParser to parse the SQL query and obtain detailed column information.
- It ensures that data types and primary key information are accurately reflected in the generated class.
-
Resource Management:
- The use of
try...finally blocks ensures that resources like FieldDeclarations, PropertyDeclarations, and ResultBuilder are properly freed.
- This conforms to good programming practices, preventing memory leaks.
-
Error Handling:
- The function assumes that the parser and database connections will handle exceptions as necessary.
- You may add additional
try...except blocks if specific error handling is required.
-
Handling Primary Keys:
- The function checks the
IsPKColumn property of each TColumnInfo to determine if the field is a primary key.
- It adds a
[PrimaryKey] attribute to the field declaration if applicable.
By making these adjustments, the function is now robust and capable of generating a Delphi class that accurately represents the structure of the SELECT query's result set, adhering to good programming practices and leveraging the enhanced SQL parser.
Example Usage:
var
SQLText: string;
ClassName: string;
Connection: TUniConnection;
ClassDefinition: string;
begin
SQLText := 'SELECT id, name, created_at FROM users;';
ClassName := 'User';
Connection := TUniConnection.Create(nil);
try
// Set up the connection parameters
Connection.ProviderName := 'MySQL';
Connection.Database := 'your_database';
Connection.Server := 'localhost';
Connection.Username := 'your_username';
Connection.Password := 'your_password';
Connection.Connect;
// Generate the class definition
ClassDefinition := GenerateDelphiClassFromSQL(SQLText, ClassName, Connection);
// Output the class definition
Writeln(ClassDefinition);
finally
Connection.Free;
end;
end;
This example assumes that you have a valid database connection. The GenerateDelphiClassFromSQL function will parse the SQL query, retrieve the necessary schema information, and generate the Delphi class definition accordingly.